如何在 Guice 中使用构造函数绑定 class

How to bind class with constructor in Guice

我想将 MyImpl 绑定到 Multibinding。但是 MyImpl 的构造函数采用参数。

final Multibinder<MyInterface> binder = Multibinder.newSetBinder(binder(), MyInterface.class)
binder.addBinding().to(MyImpl.class);

public MyImpl(Boolean myParam) ...

我不想@Inject 它,因为它是布尔值,偶尔可以在其他地方注入。所以。我可以引入一些枚举并改为注入它,那该怎么做呢?或者我可以更好地写一些

binder.addBinding().to(MyImpl.class, true);
binder.addBinding().to(MyImpl2.class, false);

左右?

I do not want to @Inject it because it's say boolean, which can be occasionally injected somewhere else. To avoid this, use Named Annotations.

方案一:

@Inject
public TextEditor(@Named("OpenOffice") SpellChecker spellChecker) { ...}

绑定代码如下:

bind(SpellChecker.class).annotatedWith(Names.named("OpenOffice")).to(OpenOfficeWordSpellCheckerImpl.class);

方案二:

在模块中加载 java-properties 并使用 java-prop-names:

private static Properties loadProperties(String name){
    Properties properties = new Properties();
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    InputStream is = loader.getResourceAsStream(name);
    try {
        properties.load(is);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }finally {
        if(is != null){
            try {
                is.close();
            } catch (IOException dontCare) { }
        }
    }
    return properties;
}

protected void configure() {
    try{
        Properties gameProperties = loadProperties("game.properties");
        Names.bindProperties(binder(),gameProperties);
    }catch (RuntimeException ex){
        addError("Could not configure Game Properties");
    };

}