Suppose we have the following 3 (top-level) classes:
@ImplementedBy(MyClass.class)
public interface MyInterface {}
public class MyClass implements MyInterface {
@Inject
MyClass(MySecondClass mySecondClass) {}
}
public class MySecondClass {}
Then the following code results in an exception (A just-in-time binding to MySecondClass was already configured on a parent injector.
):
Guice.createInjector(
binder -> binder.bind(MyInterface.class),
binder -> binder.bind(MySecondClass.class)
);
However, if you swap around the order of the modules, there is no exception:
Guice.createInjector(
binder -> binder.bind(MySecondClass.class),
binder -> binder.bind(MyInterface.class)
);
I would expect the order of the modules not to matter. Also, the exception message is distinctly odd as there is no parent injector. Is this a bug?
I am using Guice version 5.1.0.
UPDATE
I've done a bit more digging and found this open issue, with some very similar code, so I'm now pretty confident that this is something in Guice that needs to be fixed (and has been an issue for at least a decade). The issue isn't limited to the order of modules passed to createInjector
; in fact the order of bindings in a single configure
method can make a difference.