Friday, January 29, 2010

Guice 2.0: Mixing injected and non-injected parameters

Have been using Guice for a couple of years now after a friend at Google put me on to it. Guice 2.0 is great too, one thing it makes easier is mixing injector controlled parameters and non-injector controlled parameters into a constructor (I think constructor injection is way more solid than field/method injection when you can).

The feature is called AssistedInject, here is an example:

public class PersonLocator() {
@Inject
public PersonLocator(GeneralLocator locator, @Assisted String name) {
...
}
}

To instantiate PersonLocator using the injector you need to create a PersonLocatorFactory:

public interface PersonLocatorFactory {
PersonLocator create(String name);
}

Put a binding into the injector module:

bind(PersonLocatorFactory.class).toProvider(
FactoryProvider.newFactory(PersonLocatorFactory.class, PersonLocator.class));

Then to instantiate PersonLocator use an injected PersonLocatorFactory:

public PersonHunter {
@Inject
public PersonHunter(PersonLocatorFactory personLocatorFactory, String name){
PersonLocator personLocator = personLocatorFactory.create(name);
}
}