Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: load Java properties [closed]

What would be easy to read and understand, Scala code to load Java properties according to the following Java code:

    try {
        Properties prop = new Properties();
        prop.load(new FileInputStream("config.properties"));
        this.host = prop.getProperty("mongo.host");
        this.port = new Integer(prop.getProperty("mongo.port"));
        this.dbName = prop.getProperty("mongo.db");
        this.docsCollName  = prop.getProperty("mongo.coll.docs");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

Thanks!

like image 586
Anton Ashanin Avatar asked Mar 27 '13 12:03

Anton Ashanin


1 Answers

I will certainly recommend the typesafe config, written by the company behind Scala and used at least by Akka framework.

Features (quoted from wiki):

  • implemented in plain Java with no dependencies
  • extensive test coverage
  • supports files in three formats: Java properties, JSON, and a human-friendly JSON superset
  • merges multiple files across all formats
  • can load from files, URLs, or classpath
  • good support for "nesting" (treat any subtree of the config the same as the whole config)
  • users can override the config with Java system properties, java -Dmyapp.foo.bar=10 supports configuring an app, with its framework and libraries, all from a single file such as application.conf
  • parses duration and size settings, "512k" or "10 seconds"
  • converts types, so if you ask for a boolean and the value is the string "yes", or you ask for a float and the value is an int, it will figure it out.
  • JSON superset features: comments includes substitutions ("foo" : ${bar}, "foo" : Hello ${who}) properties-like notation (a.b=c) less noisy, more lenient syntax substitute environment variables

Example:

Config conf = ConfigFactory.load();
int bar1 = conf.getInt("foo.bar");
Config foo = conf.getConfig("foo");
int bar2 = foo.getInt("bar");
like image 169
fracca Avatar answered Oct 01 '22 19:10

fracca