我正在Java中通过Play使用Guice。我的班级被注释为use int number = (int)num
:
@Singleton
我的模块注册了一些绑定:
import com.google.inject.Singleton;
@Singleton
@Slf4j
public class HistoryService {
@Inject
public HistoryService(Configuration configuration) {
log.error("I am being created");
}
}
有些依赖可能很有趣:
@Override
protected void configure() {
super.configure();
bind(Flows.class).toProvider(FlowConfigProducer.class);
bind(FlowManager.class).asEagerSingleton();
bind(ApplicationLifecycle.class).to(AppLifecycleHandler.class).asEagerSingleton();
bindService(FileService.class, FileServiceImpl.class);
}
将FlowManager
注入其构造函数HistoryService
将AppLifecycleHandler
注入其构造函数中(并因此间接注入FlowManager
)我注意到HistoryService
被打印两次,并且根据堆栈跟踪被一次实例化,然后实例化I am being created
,一次被创建AppLifecycleHandler
时(按照该顺序,{ {1}}是FlowManager
的依赖项。
现在,第一个问题是FlowManager
被多次创建。它绑定为AppLifecycleHandler
。我的FlowManager
也是如此。它不应多次创建。
我也尝试过使用eagerSingleton
或HistoryService
在模块中注册HistoryService
,但无济于事。它总是创建我的服务的两个实例。是什么原因造成的?
编辑:因为我发现一个问题,提到添加bind(HistoryService.class).in(Singleton.class)
可以解决他们的问题,我也尝试过这样做,但是这并没有改变任何内容,IntelliJ已经指出,它在指定时是多余的那个。
EDIT2 :
以下是构造函数:
bind(HistoryService.class).asEagerSingleton()
注释中提到了注射器,但是至少根据获取Play指南的注射器的文档应该使用注射器的DI来完成,所以我认为我不会创建多个注射器。