Tutorial :How to use Google Guice to create objects that require parameters?


Maybe I am just blind, but I do not see how to use Guice (just starting with it) to replace the new call in this method:

public boolean myMethod(String anInputValue) {      Processor proc = new ProcessorImpl(anInputValue);      return proc.isEnabled();  }  

For testing there might be a different implementation of the Processor, so I'd like to avoid the new call and in the course of that get rid of the dependency on the implementation.

If my class could just remember an instance of Processor I could inject it via the constructor, but as the Processors are designed to be immutable I need a new one every time.

How would I go about and achieve that with Guice (2.0) ?


There is some time since I used Guice now, but I remember something called "assisted injection". It allows you to define a factory method where some parameters are supplied and some are injected. Instead of injecting the Processor you inject a processor factory, that has a factory method that takes the anInputValue parameter.

I point you to the javadoc of the FactoryProvider. I believe it should be usable for you.


You can get the effect you want by injecting a "Provider", which can by asked at runtime to give you a Processor. Providers provide a way to defer the construction of an object until requested.

They're covered in the Guice Docs here and here.

The provider will look something like

public class ProcessorProvider implements Provider<Processor> {      public Processor get() {          // construct and return a Processor      }  }  

Since Providers are constructed and injected by Guice, they can themselves have bits injected.

Your code will look something like

@Inject  public MyClass(ProcessorProvider processorProvider) {      this.processorProvider = processorProvider;  }    public boolean myMethod(String anInputValue) {      return processorProvider.get().isEnabled(anInputValue);  }  


Does your Processor need access to anInputValue for its entire lifecycle? If not, could the value be passed in for the method call you're using, something like:

@Inject  public MyClass(Processor processor) {      this.processor = processor;  }    public boolean myMethod(String anInputValue) {      return processor.isEnabled(anInputValue);  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »