[英]Guice: How to Inject an instance of the default implementation of an interface?
[英]How to specify default Enum instance for Guice?
我需要類似的東西
@DefaultInstance(Level.NORMAL)
enum Level {NORMAL, FANCY, DEBUGGING}
這將使Guice為表達式返回Level.NORMAL
injector.getInstance(Level.class)
沒有@DefaultInstance
這樣的東西。 作為一種解決方法,我嘗試了@ProvidedBy
與一個簡單的Provider
,但它不起作用。
也許重寫模塊可以幫助你。 可以使用AppLevel
模塊配置默認級別:
public class AppModule extends AbstractModule {
@Override
public void configure() {
bind(Level.class).toInstance(Level.NORMAL);
// other bindings
}
}
並且可以在小的覆蓋模塊中配置特定的一個:
public class FancyLevelModule extends AbstractModule {
@Override
public void configure() {
bind(Level.class).toInstance(Level.FANCY);
}
}
最后,只需使用特定的Level
配置創建一個覆蓋AppModule
的注入器:
public static void main(String[] args) {
Injector injector =
Guice.createInjector(
Modules.override(new AppModule()).with(new FancyLevelModule())
);
System.out.println("level = " + injector.getInstance(Level.class));
}
UPDATE
這個問題可以用稍微不同的方式解決。 假設Level
在類中用作注入字段:
class Some
{
@Injected(optional = true)
private Level level = Level.NORMAL;
}
默認級別將初始化為創建Some
實例的Some
。 如果一些Guice配置模塊聲明了某個其他級別,它將被選擇性地注入。
一個解決方案,但不幸的是沒有使用注釋,將是:
enum Level
{
NORMAL, FANCY, DEBUGGING;
static final Level defaultLevel = FANCY; //put your default here
}
然后像這樣定義模塊:
public class DefaultLevelModule extends AbstractModule
{
@Override public void configure()
{
bind(Level.class).toInstance(Level.defaultLevel);
}
}
這是問題295 ,看起來像一個非常微不足道的bug。
我已經為自己打補丁了,也許有一天,有人會解決這個非常古老的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.