Pav*_*vel 31 java dependency-injection guice
我需要绑定一个类作为两个接口的实现.它应该绑定在单一范围内.
我做了什么:
bind(FirstSettings.class).
to(DefaultSettings.class).
in(Singleton.class);
bind(SecondSettings.class).
to(DefaultSettings.class).
in(Singleton.class);
Run Code Online (Sandbox Code Playgroud)
但是,显然,它会导致创建两个不同的实例,因为它们绑定到不同的键.
我的问题是我该怎么做?
Oli*_*ire 57
Guice的wiki 有关于此用例的文档.
基本上,这是你应该做的:
// Declare that the provider of DefaultSettings is a singleton
bind(DefaultSettings.class).in(Singleton.class);
// Bind the providers of the interfaces FirstSettings and SecondSettings
// to the provider of DefaultSettings (which is a singleton as defined above)
bind(FirstSettings.class).to(DefaultSettings.class);
bind(SecondSettings.class).to(DefaultSettings.class);
Run Code Online (Sandbox Code Playgroud)
没有必要指定任何其他类:只考虑Provider
s并且答案很自然.
归档时间: |
|
查看次数: |
12809 次 |
最近记录: |