Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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) ?

like image 326
Daniel Schneller Avatar asked Jun 15 '09 14:06

Daniel Schneller


People also ask

What does bind do in Guice?

Binding is to Guice as wiring is to Spring. With bindings, we define how Guice is going to inject dependencies into a class. This module implementation specifies that an instance of DefaultCommunicatorImpl is to be injected wherever a Communicator variable is found.

What does @inject do Guice?

Note that the only Guice-specific code in the above is the @Inject annotation. This annotation marks an injection point. Guice will attempt to reconcile the dependencies implied by the annotated constructor, method, or field.

What is @inject annotation in Guice?

Annotation Type Inject. @Target(value={METHOD,CONSTRUCTOR,FIELD}) @Retention(value=RUNTIME) @Documented public @interface Inject. Annotates members of your implementation class (constructors, methods and fields) into which the Injector should inject values.

What is the use of @inject annotation?

Injectable constructors are annotated with @Inject and accept zero or more dependencies as arguments. @Inject can apply to at most one constructor per class. @Inject is optional for public, no-argument constructors when no other constructors are present. This enables injectors to invoke default constructors.


1 Answers

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.

like image 198
waxwing Avatar answered Sep 27 '22 23:09

waxwing