As previously mentioned, I'm cataloging the differences in Guice since 1.0.
This test passes in Guice 1.0, but how it does so is surprising:
public class InjectTest extends TestCase {
public void testFoo() {
Foo foo = Guice.createInjector().getInstance(InnerFoo.class)
}
class InnerFoo implements Foo {
@Inject InnerFoo() {}
}
}
The problem is that the InnerFoo
inner class is not marked static
. Therefore each instance of InnerFoo
has an implicit, invisible reference to its containing class, InjectTest
. When it creates an instance of InnerFoo
, Guice 1.0 will also build a new InjectTest
, using its default constructor. This is weird! The outer-class instance is only reachable via the implicit reference, which is awkward and unexpected.
The latest snapshots of Guice refuse to construct non-static inner classes. This will help to find bugs! And for the rare situation where non-static is desired, Providers can be used. Plus they make the choice of containing instance explicit.