【发布时间】:2012-06-01 19:02:55
【问题描述】:
我正在开发一个使用依赖注入 Google Guice 框架的项目。
可以将类与单例范围绑定,在 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() 方法将接口绑定到特定实例。
因此,在 Java 中使用以下声明来绑定 Singleton,而不是与 Singleton 范围绑定,这不是更好的方法:
bind(Foo.class).toInstance(FooImpl.getInstance());
而不是第一个?它更安全吗?这样可以有两个单例实例吗?
使用 Google Guice 声明单例的最佳方式是什么?
【问题讨论】:
标签: java dependency-injection guice