Guice singleton injection

I have a simple POJO:

public class MyPOJO {
    @Inject
    private Fizz fizz;

    private Buzz buzz;

    // rest of class omitted for brevity
}

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;

    // rest of class omitted for brevity
}

Then in my module:

public class MyModule extends AbstractModule {
    @Override
    public void configure() {
        bind(Fizz.class).annotatedWith(
            Names.named("Special-Fizz"))
            .to(Fizz.class);

        // Other bindings here...
    }

    @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.

+5
source share
2 answers

. Guice , Named, . , . , injector.inject. injectMembers? POJO , , . , - :

public class FizzTest {

  public static class MyModule extends AbstractModule {
    @Override
    protected void configure() {
    }

    @Provides
    @Singleton
    @Named("Special-Fizz")
    public Fizz providesFizz() {
      return new Fizz(true);
    }
  }

  public static class Fizz {
    boolean special = false;
    public Fizz() {}
    public Fizz(boolean special) {
      this.special = special;
    }
  }

  public static class MyPOJO {
    @Inject @Named("Special-Fizz")
    private Fizz fizz;

    @Inject
    private Fizz otherFizz;
  }

  @Test
  public void test() {
    MyModule mod = new MyModule();
    Injector injector = Guice.createInjector(mod);

    MyPOJO pojo = injector.getInstance(MyPOJO.class);
    assertTrue(pojo.fizz.special);
    assertTrue(!pojo.otherFizz.special);
  }

}
+3

Guice @Provides Fizz. Fizz, providesFizz()

bind(Fizz.class)
    .annotatedWith(Names.named("Special-Fizz")
    .toInstance(providesFizz());

, Guice , Fizz "Special-Fizz", Fizz "" .

: , , . , .

+2

All Articles