Search code examples
constructorbindingguice

How to bind class with constructor in Guice


I want to bind MyImpl to Multibinding. But MyImpl's constructor takes parameter.

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

public MyImpl(Boolean myParam) ...

I do not want to @Inject it because it's say boolean, which can be occasionally injected somewhere else. So. I can introduce some Enum and inject it instead, how then to do this? Or can I better just write somehow

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

or so?


Solution

  • 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.

    Solution One:

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

    Here is the binding code:

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

    Solution Two:

    Load java-properties in a module and use the 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");
        };
    
    }