Friday, March 14, 2008

Create a Guice Injector Using Multiple Modules

This is a very short note, but I spent too much time on Google looking for this answer and I wanted to provide a concise bit of information about it. It has recently become necessary for us to separate our Guice configuration into multiple Guice modules. We tend to have some dependencies that are project specific and others that typically remain constant from one project to another. I didn't see mention of this in the Guice guide. So, here is the information:

Guice.createInjector() can take a variable number of Modules. So, it is trivial to do this:

Guice.createInjector(myProjectDependencies, myDatabaseDependencies) and so on.

This will really help to prevent duplicating binding logic from one project to the next. We are separating our data-tier module out from project-specific bindings.

Again, all of this is trivial, but since I didn't readily find the answer on Google earlier, I wanted to put it out.

Another interesting note is that it is possible to bind to classes in module A that need bindings from module B while at the same time bind to classes in module B that need bindings from module A. Very slick.

1 comment:

Antony Stubbs said...

"Another interesting note is that it is possible to bind to classes in module A that need bindings from module B while at the same time bind to classes in module B that need bindings from module A. Very slick."

Care to post an example of this? I'd be keen to see it.

________________________________
http://stubbisms.wordpress.com