I have a simple POJO:
public class MyPOJO {
@Inject
private Fizz fizz;
private Buzz buzz;
}
I would like to configure my Guice module so that there are two types of Fizzes that it introduces:
- Special, globally-singleton
Fizzinstance; and - Other (non-special) instances
Fizz
I want to MyPOJObe added with a special / single instance. So I changed my code:
public class MyPOJO {
@Inject @Named("Special-Fizz")
private Fizz fizz;
private Buzz buzz;
}
Then in my module:
public class MyModule extends AbstractModule {
@Override
public void configure() {
bind(Fizz.class).annotatedWith(
Names.named("Special-Fizz"))
.to(Fizz.class);
}
@Provides @Singleton
private Fizz providesFizz() {
return new Fizz(true, "Special", 12.0);
}
}
But when I try unit test (JUnit 4.10), this is:
public class MyTest {
@Named("Special-Fizz") private Fizz specialFizz;
@Test
public void usingNamedShouldInjectSpecialFizz() {
MyModule mod = new MyModule();
Injector injector = Guice.createInjector(mod);
specialFizz = injector.getInstance(Fizz.class);
Assert.assertTrue(specialFizz != null);
}
}
It passes. So far, so good. But if I changed the name of the field specialFizz:
@Named("Special-Fuzz-This-Shouldnt-Work") private Fizz specialFizz;
And run the test again, it will pass anyway. What for?!? Where am I going out of my way here? Thanks in advance.
source
share