没有注射器的guice注射
guice injection without injector
下面是我的模块class
public class ABCModule extends AbstractModule {
@Override
protected void configure() {
install(new JpaPersistModule(Configuration.get("error-persister")));
bind(DBService.class).to(DBServiceImpl.class).in(Singleton.class);
bind(DBRepository.class).to(DBRepositoryImpl.class).in(Singleton.class);
}
@ProvidesIntoOptional(ProvidesIntoOptional.Type.ACTUAL)
public ErrorHandler getErrorHandler() {
return new ABCHandler();
}
}
ABCHandler 有
private final DBService dbService;
@Inject
public ABCHandler() {
Injector injector = Guice.createInjector(new ABCModule());
injector.getInstance(PersistenceInitializer.class);
this.dbService = injector.getInstance(DBService.class);
}
@Override
public void handle() {
dbService.store("abc");
}
ABCModule
实例被创建并传递给一些通用模块。如您所见,ABCModule
提供了 ABCHandler
并且 ABCHandler
再次使用 ABCModule
来创建注入器和服务实例。它有效,但我知道这是不正确的。 Module
被调用了两次。如何在 ABCHandler
中注入 dbService
而无需使用注入器或创建模块实例。我不想创建一个虚拟的空模块来创建实例。你能建议一下吗?如果我只是在 dbService
上使用 @Inject
而不使用注入器,它就会变成 null。我在 Module
中使用 Provider
,可以为 dbService
做类似的事情。或任何其他解决方案?
DbService
已经可以注入了,你可以在 getErrorHandler
方法中传递它
@ProvidesIntoOptional(ProvidesIntoOptional.Type.ACTUAL)
public ErrorHandler getErrorHandler(DBService dbService) {
return new ABCHandler(dbService);
}
这种情况下ABCHandler
构造函数可以改成这样
@Inject
public ABCHandler(DBService dbService) {
this.dbService = dbService;
}
您可以在此处找到更多详细信息
Accessing Guice injector in its Module?
下面是我的模块class
public class ABCModule extends AbstractModule {
@Override
protected void configure() {
install(new JpaPersistModule(Configuration.get("error-persister")));
bind(DBService.class).to(DBServiceImpl.class).in(Singleton.class);
bind(DBRepository.class).to(DBRepositoryImpl.class).in(Singleton.class);
}
@ProvidesIntoOptional(ProvidesIntoOptional.Type.ACTUAL)
public ErrorHandler getErrorHandler() {
return new ABCHandler();
}
}
ABCHandler 有
private final DBService dbService;
@Inject
public ABCHandler() {
Injector injector = Guice.createInjector(new ABCModule());
injector.getInstance(PersistenceInitializer.class);
this.dbService = injector.getInstance(DBService.class);
}
@Override
public void handle() {
dbService.store("abc");
}
ABCModule
实例被创建并传递给一些通用模块。如您所见,ABCModule
提供了 ABCHandler
并且 ABCHandler
再次使用 ABCModule
来创建注入器和服务实例。它有效,但我知道这是不正确的。 Module
被调用了两次。如何在 ABCHandler
中注入 dbService
而无需使用注入器或创建模块实例。我不想创建一个虚拟的空模块来创建实例。你能建议一下吗?如果我只是在 dbService
上使用 @Inject
而不使用注入器,它就会变成 null。我在 Module
中使用 Provider
,可以为 dbService
做类似的事情。或任何其他解决方案?
DbService
已经可以注入了,你可以在 getErrorHandler
方法中传递它
@ProvidesIntoOptional(ProvidesIntoOptional.Type.ACTUAL)
public ErrorHandler getErrorHandler(DBService dbService) {
return new ABCHandler(dbService);
}
这种情况下ABCHandler
构造函数可以改成这样
@Inject
public ABCHandler(DBService dbService) {
this.dbService = dbService;
}
您可以在此处找到更多详细信息 Accessing Guice injector in its Module?