ProvisionListener gets called multiple times for a singleton if using private modules
- Dominant language
- Java
- Stars
- 12.7k
- Forks
- 1.7k
- Avg merge
- 11m
- Merged PRs (30d)
- 2
Description
[this is more a documentation issue as the reason is straightforward]
Consider this unit test:
```java
public void testPrivateModuleSingletonDoubleProvisions() {
final Counter counter = new Counter();
Injector injector = Guice.createInjector(
new ProvidesModule(),
new PrivateProvidesModule(),
binder -> binder.bindListener(new AbstractMatcher>() {
@Override
public boolean matches(Binding binding) {
return binding.getKey().getRawType() == Stuff.class;
}
}, counter),
Binder::requireExplicitBindings,
Binder::requireAtInjectOnConstructors
);
injector.getInstance(UseStuff.class);
assertEquals("provisioned singleton twice", 1, counter.count);
}
static class Stuff { }
@Retention(RUNTIME)
@Target({FIELD, PARAMETER, METHOD})
@Qualifier
public @interface Marker {}
static class UseStuff {
private final Stuff stuff;
@Inject
public UseStuff(Stuff stuff) {
this.stuff = stuff;
}
}
private static class ProvidesModule implements Module {
@Override
public void configure(Binder binder) {
}
@Provides
@Singleton
@Marker
public Stuff getStuff() {
return new Stuff();
}
}
private static class PrivateProvidesModule extends PrivateModule {
@Override
protected void configure() {
bind(UseStuff.class).in(Scopes.SINGLETON);
bind(Stuff.class).toProvider(StuffProvider.class).in(Scopes.SINGLETON);
expose(UseStuff.class);
}
static class StuffProvider implements Provider {
private final Injector injector;
@Inject
public StuffProvider(Injector injector) {
this.injector = injector;
}
@Override
public Stuff get() {
return injector.getInstance(Key.get(Stuff.class, Marker.class));
}
}
}
```
The attached counter is incremented twice for the same object. It is called once when the object is provisioned in the private module and again when the object itself is provisioned.
Contributor guide
Assessment
This issue has not been assessed yet.