matteobaccan / owner

Get rid of the boilerplate code in properties based configuration.
https://matteobaccan.github.io/owner/
BSD 3-Clause "New" or "Revised" License
917 stars 213 forks source link

Recommended usage pattern with dependency injection framework? #147

Open sanity opened 9 years ago

sanity commented 9 years ago

Are there any recommended usage patterns for using Owner in conjunction with a dependency injection framework like Guice?

Guice already has basic support for reading parameters from a .properties file and injecting into classes, but it's fairly bare-bones. It would be nice if Owner could be used with Guice in a "Guiceful" way.

marx-freedom commented 9 years ago

I'm using something like this

public interface SomeProperties extends org.aeonbits.owner.Config {

    @DefaultValue("bar")
    @Key("foo")
    String getFoo();
}

class SomePropertiesImpl implements SomeProperties {

    private SomeProperties delegate;

    public SomePropertiesImpl() {
        this.delegate = org.aeonbits.owner.ConfigFactory.create(SomeProperties.class, System.getProperties());
    }

    @Override
    public String getFoo() {
        return delegate.getFoo();
    }
}

in Guice module:

bind(SomeProperties.class).to(SomePropertiesImpl.class).in(SINGLETON);

in code:

@Inject private SomeProperties props;
zldelgado commented 4 years ago

In my case, the SomeProperties interface looks more like a ManyProperties interface, so to avoid creating boilerplate you can rely on Project Lombok's @Delegate annotation.

public interface ManyProperties extends org.aeonbits.owner.Config {

    @DefaultValue("bar")
    @Key("foo")
    String getFoo();

    // Many more properties
    // [...]

}

class ManyPropertiesImpl implements ManyProperties {

    @Delegate(types = ManyProperties.class)
    private final ManyProperties delegate;

    public ManyPropertiesImpl() {
        this.delegate = org.aeonbits.owner.ConfigFactory.create(ManyProperties.class, System.getProperties());
    }

    // To access to 'toString' method it is necessary to specify it explicitly
    public String toString() {
        return this.delegate.toString();
    }

}

The rest of the code is like @marx-freedom suggested.