问题
I have recently started using Google guice DI framework and am quite new to it. I am facing below problem - @inject returns null always and have to call injector to inject various references.
This is my AbstractModule class
public class AppModule extends AbstractModule {
private static final Injector injector = Guice.createInjector(new AppModule());
private final Vertx vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(
new DropwizardMetricsOptions().setEnabled(true)
));
private final com.test.reactivex.db.service.DBService dbService;
public AppModule() {
this.dbService = DBService.createProxy(this.vertx, DB_SERVICE_ADDRESS);
}
@Override
protected void configure() {
bind(Vertx.class).toInstance(this.vertx);
bind(EventBus.class).toInstance(this.vertx.eventBus());
bind(FileSystem.class).toInstance(this.vertx.fileSystem());
bind(SharedData.class).toInstance(this.vertx.sharedData());
bind(com.test.reactivex.db.service.DBService.class).toInstance(this.dbService);
bind(AppConfig.class).toProvider(AppConfigProvider.class).in(Singleton.class);
//requestStaticInjection(AppDependenciesInjector.class);
logger.info("Google guice module configuration done");
}
@Provides
public static AppConfig appConfig() {
return injector.getInstance(AppConfig.class);
}
public static Injector getInjector() {
return injector;
}
}
This is how I am using injector to inject dependencies, but problem is that I have to use injectors again.
public class GraphQLRouter {
@Inject
private static AppConfig config;
@Inject
private com.test.reactivex.auth.service.DBService dbService;
public GraphQLRouter() {
// below code I want to avoid
if (dbService == null) {
dbService = AppModule.getInjector().getInstance(com.test.reactivex.auth.service.DBService.class);
}
}
//below code I want to avoid
static {
if (config == null)
config = AppModule.getInjector().getInstance(AppConfig.class);
}
来源:https://stackoverflow.com/questions/61853490/how-to-avoid-google-guice-injector-getinstance-repetative-calls-due-to-null