I have a class SomeClass
and a SomeModule
to register it with Guice.
I found out that the constructor SomeClass
is only called by SomeModule
, and that SomeModule
is the only place where binding for SomeClass
happens.
This means that the @Inject
on SomeClass
's constructor is not needed since prop1
and prop2
are injected inside SomeModule
and passed to the constructor. And the testing also seems to prove my findings.
My question is that what Guice will do when it sees a @Inject
like this?
Also what side effect will there be if I have an excessive @Inject
?
public static class SomeModule extends PrivateModule {
@Provides
@Singleton
@Exposed
private SomeClass someClass( SomeObject prop1, String prop2) {
return new SomeClass(prop1, prop2);
}
}
public class SomeClass {
@Inject // unnecessary
public SomeClass(SomeObject prop1, String prop2){
...
}
}
If my understanding is correct, you @Inject
a constructor when you want to inject objects managed by Guice into the parameters of the constructor.
e.g. if I have bind(SomeClass.class).in(Singleton.class)
and bindings for prop1
and prop2
, it makes sense to @Inject
SomeClass
constructor in order to inject prop1
and prop2
into the constructor.
But since this isn't the case, this makes the @Inject
here unnecessary
Cheers
Quoting @Deepak's comment as the answer:
You need @Inject if you were defining a binding in the configure method instead of creating a Provider for this class. When you define a binding in the configure method, you are telling Guice to instantiate the object for you. That is when it looks for a constructor with @Inject to figure out what dependencies it has to Inject to construct that object. In case of Provider, you are creating the object yourself by passing all the dependencies required for that class as arguments. So, @Inject has no meaning at that case