我在独立库中有一个 Service
接口(interface)和 ServiceImpl
实现类,我不想对 Guice 有任何依赖。
但是我在使用 Service
的应用程序中使用 Guice。在这个应用程序中,我想将 Service
绑定(bind)到 ServiceImpl
,并且我希望 ServiceImpl
是一个单例。
通常我会通过使用 @Singleton
注释 ServiceImpl
然后像这样绑定(bind)
bind(Service.class).to(ServiceImpl.class);
但是由于 ServiceImpl
不依赖于 Guice,我不能添加注释,或者用任何 Guicy 修改它的源。
我可以在应用程序模块中将 Service
绑定(bind)到 ServiceImpl
,但我不清楚如何在外部将 ServiceImpl
配置为单例' 在应用程序的模块(或其他)中。
最佳答案
参见:https://github.com/google/guice/wiki/Scopes
Scopes
Guice uses annotations to identify scopes. Specify the scope for a type by applying the scope annotation to the implementation class.
Scopes can also be configured in bind statements:
bind(Service.class).to(ServiceImpl.class).in(Singleton.class);
应该适合你。
关于java - Guice:在没有 @Singleton 或以其他方式修改实现的情况下配置单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31213672/