Reputation: 53
I have this problem.
Consider I have classes definitions like:
public interface ABCInterface
{
}
And its implementation:
public class ABCImpl
{
@Inject
private XYZ xyz;
}
When the Guice Config is like this:
public class MasterConfig extends AbstractModule
{
@Override
protected void configure()
{
// TODO Auto-generated method stub
bind(ABCInterface.class)
.to(ABCImpl.class);
}
}
And run it, then everything works fine and XYZ gets injected into it.
But when I use provider methods like this:
public class MasterConfig extends AbstractModule {
@Override
protected void configure() {
// TODO Auto-generated method stub
}
@Provides
public ABCInterface abc() {
return new ABCImpl();
}
}
Then, in this case, I get a null pointer exception when I try to use the injected XYZ, because that object remains null. I am suspecting, this is beacuse, I am returning a new object of ABCImpl and hence Guice is not able to build a dependency graph. Please correct me if I am wrong here?
Can anyone suggest, how to write the Provider method, so that everything gets injected properly like it does when I mention in the configure method.
Upvotes: 3
Views: 2819
Reputation: 12922
Indeed, when you write new ABCImpl()
, Guice doesn't get a chance to inject its dependencies. You can do this:
@Provides
ABCInterface abc(ABCImpl impl) {
return impl;
}
but you might as well just write bind(ABCInterface.class).to(ABCImpl.class);
in that case, unless your provider method has some extra logic.
Upvotes: 3