I am pretty new to google guice .
I am writing a nexus plugin where nexus injects some classes . for example say the class to be injected in class A.
Now before that class A is injected, I have another class B that was instantiated and inside it I have a method where an object (say obj) is initialised .
I have to pass this initialised object to the class A.
Normally if instantiation is under our control I will do as
A a = new A();
A.setObject(obj);
But now given that the class will be injected by the system , I don't know how to pass this initialised object to this class A.
If I understand correctly, you have something like
This design does not follow DI principles and should be refactored. You should let Guice create your
C
instance. In that case you will have something likeAnd here you have
C
automatically injected both intoA
andB
.If you really cannot refactor you code, consider using providers then:
In this case a provider is used to create
A
and set itsC
dependency.But sometimes even that is not enough (e.g. when your
B.getC()
behavior depends on user input). In that case you have to use assisted inject extension:In the last example two object will be injected into
A
viaaf.create(c)
invocation: first, thatc
you have provided, and second, and instance ofOther
class which is resolved automatically by Guice. In other words, assisted inject allows you to instantiate classes which will have one part of their dependencies resolved by you, and other part - by Guice.