Guice:在没有 @Singleton 或以其他方式修改实现的情况下配置单例

Guice: Configure singleton without @Singleton or otherwise modifying implementation

我在独立库中有一个 Service 接口和 ServiceImpl 实现 class,我不想对 Guice 有任何依赖。

但是我在使用 Service 的应用程序中使用 Guice。在这个应用程序中,我想将 Service 绑定到 ServiceImpl,并且我希望 ServiceImpl 成为一个单例。

通常我会用 @Singleton 注释 ServiceImpl 然后像这样绑定

bind(Service.class).to(ServiceImpl.class);

但是由于 ServiceImpl 不依赖于 Guice,我不能添加注释,或者用任何 Guicy 修改它的源代码。

我可以在应用模块中将 Service 绑定到 ServiceImpl,但我不清楚如何在应用模块中将 ServiceImpl 配置为单例 'externally' (或其他)。

参见: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); 应该适合你。