简体   繁体   English

Singleton Dagger2组件

[英]Singleton Dagger2 components

I'm using Dagger2 in a google appengine project and I have several servlets that make use of, what should be, a singleton instance of a given object (MyObject). 我在Google Appengine项目中使用Dagger2,我有几个servlet,它们应该使用给定对象(MyObject)的单例实例。

@Singleton
@Component(modules = {MyModule.class})
public interface MyComponent {
  IMyObject object();
}

I then need DaggerMyComponent.create() to be a singleton too so that I can get the same IMyObject across all servlets. 然后,我也需要DaggerMyComponent.create()也要成为一个单例,以便可以在所有servlet中获得相同的IMyObject。 To do so, I added a 为此,我添加了一个

DaggerMyComponent INSTANCE = DaggerMyComponent.create()

to my MyComponent interface. 到我的MyComponent界面。 However, that still allows create() to be called again by mistake and it doesn't necessarily look like a pretty solution to me. 但是,这仍然允许再次错误地调用create(),对于我来说,它不一定是一个不错的解决方案。

Any ideas? 有任何想法吗?

Thanks! 谢谢!

Unfortunately the docs seem to be saying that Dagger doesn't provide such a limitation so far as for version 2.0.1 不幸的是,文档似乎在说Dagger对于2.0.1版本没有提供这样的限制。

In order to get the proper behavior associated with a scope annotation, it is the caller's responsibility to instantiate new component instances when appropriate. 为了获得与范围注释关联的正确行为,在适当时,实例化新的组件实例是调用者的责任 A Singleton component, for instance, should only be instantiated once per application, while a RequestScoped component should be instantiated once per request. 例如,一个Singleton组件仅应在每个应用程序中实例化一次,而RequestScoped组件应在每个请求中实例化一次。

http://google.github.io/dagger/api/latest/dagger/Component.html http://google.github.io/dagger/api/latest/dagger/Component.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM