Injecting environment variables with Guice

This is rather mundane, but I couldn’t resist.

Dependency Injection is cool, as it allows you to dynamically configure the dependency graph of the classes in your application. Now very often, your application also needs to take into account some environment variables to do something useful: the address and port of the microservice to connect to, the username and password of some databases, etc… Since it is just another kind of configuration, it is probably a good idea to “guice” the environment variables directly into the classes, so that you don’t need to write up a separated Configuration class and intrude it into every here and there.

The easiest way to do this is to use some form of Instance Binding, but I don’t like the “Named” annotation because it uses a string as the identifier, which is error-prone. Moreover, it will be nice if we can see all the environment variables in one place, instead of all over places in the codebase.

guice-property does just that. It allows you to define all the environment variables in one place:

SERVER("MY_SERVER", "my.server", "localhost", "The server"),
PORT("", "my.port", "1234", "The port"),

and then use a special annotation @Prop to inject them into wherever they are needed:

import phvu.prop.{Prop, Property}

class PropertyUser @Inject()
(@Prop(Property.SERVER) val server: String, @Prop(Property.PORT) val port: Int) {

  def run() = {
    println(s"I am on $server:$port")

Simple enough?

Check it out and let me know what you think.


Leave a Reply

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

You are commenting using your 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