Jialun Liu Jialun Liu - 11 months ago 38
Java Question

Guice Inject Field in class NullPointerException, circular dependency issue introduced

I need to use create a singleton in Guice defined in separate library.

@RequiredArgsConstructor
public class Operator {

@NonNull private final Catalog catalog;

@Inject private Evaluator evaluator;
...
}


One of the problem is that this class introduces circular dependency, Evaluator -> Operator -> Evaluator. I know it is not a good design, but is consumed by other packages, there is no easy way to change it. This library has the beans created using Spring framework, where this circular dependency could be handled.

Now I need to create an instance of the Operator in a service based on Guice, I have created the singleton Evaluator in the service, but it was not able to inject the singleton into the Operator.

@Provides @Singleton
public Operator operator(final Catalog catalog)
{
return new Operator(catalog);
}

@Provides @Singleton
public Evaluator evaluator(final Operator operator) {
return new Evaluator(operator);
}


Since the Operator class is being used for other services based on Spring framework, I would prefer not to change it. What can I do to make the Guice able to inject the Evaluator into Operator?

Thanks in advance for any help!

Answer Source

In this circular dependency case, Guice is not smart enough to help injecting dependencies, you can specifically ask Guice to inject dependencies for this class.

@Provides @Singleton
public Operator operator(final Catalog catalog) 
{
    return new Operator(catalog);
}

And then injector.injectMembers(injector.getInstance(Operator.class)) would help inject the required dependencies.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download