我正在开发一个使用依赖注入(inject) Google Guice 框架的项目。
可以将类与单例范围绑定(bind),在 Guice 中如下:
bind(Foo.class).to(FooImpl.class).in(Scopes.SINGLETON);
如果 FooImpl
类本身就是一个真正的单例类:
public class FooImpl implements Foo{
public static final FooImpl INSTANCE = new FooImpl();
public static FooImpl getInstance(){...}
// ...
}
或
public class FooImpl implements Foo{
private FooImpl instance = null;
private FooImpl(){...}
public static FooImpl getInstance(){
if(instance == null)
instance = new FooImpl();
return FooImpl();
// ...
}
// ...
}
因此,可以在项目中声明两个单例,第一个由 Guice 声明,第二个由 getInstance()
传统方式声明。
Google Guice 还可以使用 toInstance()
方法将接口(interface)绑定(bind)到特定实例。
因此,在 Java 中使用以下声明绑定(bind) Singleton 不应该是绑定(bind) Singleton 的更好方法:
bind(Foo.class).toInstance(FooImpl.getInstance());
而不是第一个?是不是更安全?是否可以通过这种方式拥有两个单例实例?
使用 Google Guice 声明单例的最佳方式是什么?
最佳答案
您建议的第一种方法是首选:
bind(Foo.class).to(FooImpl.class).in(Scopes.SINGLETON);
这允许 Guice 根据需要在 FooImpl 中执行依赖注入(inject)。正如您上次建议中那样,使用 toInstance()
手动绑定(bind)到实例时,这是不可能的。
最后,单例设计模式is an anti-pattern for many reasons 。注意,这里指的是使用getInstance()
等实现;在应用程序的生命周期中拥有一个类的单个实例(就像 Guice 的 SINGLETON
范围中的对象)无论如何都不错。
另请参阅Guice's page on scopes了解单例作用域的一些使用指南。
关于java - 具有依赖注入(inject)的两个单例实例(Google Guice),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10855937/