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

标签 java binding singleton guice

我在独立库中有一个 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/

相关文章:

java - BufferedReader 的 read() 方法如何工作?

java - 在 Java 中嵌套 try/catch 语句是否可以接受?

xaml - 具有数据触发器的交替索引

ruby - 动态地将模块中的方法添加到类的特定实例

c++ - 我什么时候应该在 C++ 中使用单例类?

python - 自毁构造函数 == 单例?

java - 如何在Android键盘中设置关闭选项

java - Bill Pugh 实现 Singleton 的方法导致 "Out-of-order Write"?

binding - 在 Rust 库中处理 API key 的最惯用方法?

java - jgoodies 绑定(bind) + 合并频繁更改