Luigi is a passionate software developer working in Java since 2000. In 2001 he co-founded the Java User Group Torino, the first local JUG in Italy. Quickly after that, many other JUGs have born in Italy following JUG Torino's example. Since some years now, he is working as free lance software consultant between Italy, Germany, UK and Switzerland, on several industries. His personal interests include software, science fiction books and movies, traveling, photography and good food. Luigi is a DZone MVB and is not an employee of DZone and has posted 19 posts at DZone. You can read more from them at their website. View Full User Profile

Introducing OWNER, a Tiny Framework for Java Properties Files.

01.01.2013
| 4539 views |
  • submit to reddit

I never liked to create “wrapper” classes for properties files. Do you know… those classes like:

public class MyAppConfig {
    private static Properties p = ...;

    public static String serverName() {
        return p.getProperty("server.name");
    }

    public static int serverPort() {
        return Integer.parseInt(p.getProperty("server.port"));
    }

    ....
}

There’s nothing really bad about those classes. Only that they don’t do actually anything useful; plus, you need to keep things in sync with the properties file associated.

So, I always preferred to directly use Properties.getProperty() and pass a config properties to objects:

   
public class MyBusinessClass {
    private final Properties conf;
    public MyBusinessClass(..., Properties conf) {
        this.conf = conf;
    }    

    public void doSomething() {
        String serverName = conf.getProperty("server.name");
        int serverPort = Integer.parseInt(conf.getProperty("server.port"));
    }
}

99% of the times, you need a configuration setting in a single point. So that’s good enough, and I don’t have to write (and keep in sync) a class that I can spare.

But… what about this?

public interface MyAppConfig extends Config {

    @DefaultValue("foobar.com")
    @Key("server.name");
    String serverName();

    @DefaultValue("80");
    @Key("server.port");
    int serverPort();
    ...
}

Add to this, a smart -annotation based- configuration loading:

@Sources({"file:~/.myapp.config", "file:/etc/myapp.config", "classpath:foo/bar/baz.properties"})
public interface MyAppConfig extends Config {
...

And a simple instantiation:

MyAppConfig conf = ConfigFactory.create(MyAppConfig.class);

And you have OWNER. A little configuration framework based on Java properties.

BSD license.
Credits to Google GWT, that does similar things with i18n.


 

Published at DZone with permission of Luigi Viggiano, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)