Category Archives: Scala

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:

The Bright Side of Java & Linux

Yet another Java blog


Bringing empathy into knowledge workers life

%d bloggers like this: