Guice 初学者 - 如何绑定具体 类 - 单例?
Guice Beginner - How to bind concrete classes - Singleton?
我想将 class 绑定到一个实例,但 Guice 不允许我这样做,给我 绑定点自身 错误。我也希望实例是一个单例。
所以要提供更多背景知识。我有一个 class 我想绑定,但我不能,因为 bindClass 和 instanceClass 必须不同。
//This fails when bindClass==instanceClass
bind((bindClass)).to(instanceClass).in(Singleton.class);
这里有一个标题为 "Guice Beginner - How to bind concrete classes" 的问题:
Guice Beginner - How to bind concrete classes?
接受的答案是不绑定,让 "Just In Time" 绑定完成工作。
但是如果你想要实例的 单例 怎么办?
// eager singleton always
bind(YourClass.class).asEagerSingleton();
// eager in prod, lazy in dev
bind(YourClass.class).in(Singleton.class);
这与 bind
声明的许多其他变体一起列在 Binder class-level docs:
bind(ServiceImpl.class).in(Singleton.class);
// or, alternatively
bind(ServiceImpl.class).in(Scopes.SINGLETON);
Either of these statements places the ServiceImpl class into singleton scope. Guice will create only one instance of ServiceImpl and will reuse it for all injection requests of this type. Note that it is still possible to bind another instance of ServiceImpl if the second binding is qualified by an annotation as in the previous example. Guice is not overly concerned with preventing you from creating multiple instances of your "singletons", only with enabling your application to share only one instance if that's all you tell Guice you need.
虽然简单地用 @Singleton
标记 class 并依赖 JIT 绑定也可以,但根据 Guice 将绑定放置在模块中是有好处的验证您的图表 并急切地执行初始化。这在服务器上下文中特别有用,因为更有可能在开始将实时流量重定向到新加载的服务器实例之前进行初始化。
在 Scopes wiki page 上查看有关 eager/lazy 单例加载的更多信息。
我想将 class 绑定到一个实例,但 Guice 不允许我这样做,给我 绑定点自身 错误。我也希望实例是一个单例。
所以要提供更多背景知识。我有一个 class 我想绑定,但我不能,因为 bindClass 和 instanceClass 必须不同。
//This fails when bindClass==instanceClass
bind((bindClass)).to(instanceClass).in(Singleton.class);
这里有一个标题为 "Guice Beginner - How to bind concrete classes" 的问题:
Guice Beginner - How to bind concrete classes?
接受的答案是不绑定,让 "Just In Time" 绑定完成工作。
但是如果你想要实例的 单例 怎么办?
// eager singleton always
bind(YourClass.class).asEagerSingleton();
// eager in prod, lazy in dev
bind(YourClass.class).in(Singleton.class);
这与 bind
声明的许多其他变体一起列在 Binder class-level docs:
bind(ServiceImpl.class).in(Singleton.class); // or, alternatively bind(ServiceImpl.class).in(Scopes.SINGLETON);
Either of these statements places the ServiceImpl class into singleton scope. Guice will create only one instance of ServiceImpl and will reuse it for all injection requests of this type. Note that it is still possible to bind another instance of ServiceImpl if the second binding is qualified by an annotation as in the previous example. Guice is not overly concerned with preventing you from creating multiple instances of your "singletons", only with enabling your application to share only one instance if that's all you tell Guice you need.
虽然简单地用 @Singleton
标记 class 并依赖 JIT 绑定也可以,但根据 Guice 将绑定放置在模块中是有好处的验证您的图表 并急切地执行初始化。这在服务器上下文中特别有用,因为更有可能在开始将实时流量重定向到新加载的服务器实例之前进行初始化。
在 Scopes wiki page 上查看有关 eager/lazy 单例加载的更多信息。