![](/img/trans.png)
[英]Guice: How to get instance of Singleton without injector or using Constructor Injection
[英]guice injection without injector
下面是我的模塊類
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
被調用兩次。 如何注入dbService
內ABCHandler
,而不必使用注射器或創建模塊實例。 我不想創建一個虛擬的空模塊只是為了創建實例。 你能建議一下嗎? 如果我僅在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;
}
您可以在這里找到更多詳細信息, 在其模塊中訪問Guice進樣器?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.