简体   繁体   中英

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!

Try this, I hope it will help you.

public class Evaluator {
  @Inject public Evaluator(Operator op) {
    // ...
  }
}
public class Operator {
  @Inject public Operator(map m) {
    // ...
  }
}
public class map {
  @Inject public map(Provider<Evaluator> EvaluatorProvider) {
    // ...
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM