I have a class where I need to inject a variable but the constructor is not guice injected.
public class Foo{
private boolean x;
public Foo(){
//sets some variables
}
@Inject
public void setX(boolean x){
this.x=x;
}
}
The value of x is not getting injected. Is it necessary to use injection in constructor for guice to recognize method injection? Do I need to call this method from some other class for this to work? Thanx in advance
If you're going to use Guice to @Inject
Foo
then Guice needs to create the object - either from the injector or from another @Inject
point in separate class. Guice can't help you inject objects that it didn't create.
In this case it's not necessary to add @Inject
to the constructor because Guice can automatically inject a no argument constructor. For example:
public class MethodInjectionTest {
static class Foo {
private boolean x;
public Foo(){
//sets some variables
}
@Inject
public void setX(boolean x){
this.x=x;
}
}
Injector i = Guice.createInjector(new AbstractModule() {
protected void configure() {
bind(Boolean.class).toInstance(Boolean.TRUE);
}
});
@Test
public void methodInjection() {
Foo foo = i.getInstance(Foo.class);
assertThat(foo.x, is(true));
}
// EDIT: An example based on the comment by @JeffBowman
@Test
public void memberInjection() {
Foo foo = new Foo();
i.injectMembers(foo);
assertThat(foo.x, is(true));
}
}
If your real world class has a need to mix Guice controlled dependencies with client provided dependencies during construction have a look at assisted inject
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.