Guice Modules for Play apps


As a former Java / Spring developer I liked the concept of configuration classes (i.e. Java classes annotated with the Spring @Configuration annotation).

I recently started to work with Play 2.3.x and Guice and one smell that I immediately found was the duplication in creating RedisClient objects.

Basically each Dao was reading the configuration and creating its own copy of the bean. While most of the RedisClient(s) were configured slightly differently, some Daos contained literally copy-and-paste code.

After some research I came across the Guice AbstractModule class and the @Provides annotation. For those of you familiar with Java + Spring a Guice Module is similar to a Java class annotated with the Spring @Configuration.

Below there is an example of the MyRedisService that relies on two RedisClients. The two RedisClients are configured in the Config Guice Moducle and individuated by their names.

The Config Module:

The Service:

In order to link everything together and inform Guice of the new Config Module, it’s necessary to add:

play.modules.enabled += "config.Config"

in the configuration.

Full example and app available in: https://github.com/nemo83/play-scala-example

About giannigar

Senior Software Engineer - Groupon - Dublin, Ireland

Posted on November 16, 2015, in Programming, Scala and tagged , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Bright Side of Java & Linux

Yet another Java blog

mysoftwarequality

Bringing empathy into knowledge workers life

Jess & the City

Cynical ramblings of a Latin girl living in Dublin

%d bloggers like this: