New feature in 0.6: Multiple configuration fields

31 views
Skip to first unread message

Henning Schmiedehausen

unread,
Nov 28, 2010, 2:39:42 PM11/28/10
to config-magic
Multiple configuration fields
=============================

A new feature in the 0.6 release allows using multiple configuration
properties to satisfy an @Config annotation.

This can be used instead of @Default() annotations to allow fallback
values while still making them configurable (@Default values are
constant and compiled in).

Example
-------

Properties file:

default_host=localhost
default_name=testdb
default_user=testuser
default_pass=verysecret
#
db1_host=db1
#
db2_host=db2
db2_name=large_testdb
#
db3_host=db3
db3_user=testsuer


Configuration bean:

public abstract class DBConfig
{
@Config({"${db_name}_host","default_host"})
public abstract String getDBHost();

@Config({"${db_name}_name","default_name"})
public abstract String getDBName();

@Config({"${db_name}_user","default_user"})
public abstract String getDBUser();

@Config({"${db_name}_pass","default_pass"})
public abstract String getDBPass();
}



Code snippet using the Bean:

ConfigurationObjectFactory c = new
ConfigurationObjectFactory(System.getProperties());
String dbname = System.getProperty("db_name");
DBConfig dbc = c.buildWithReplacements(DBConfig.class,
Collections.singletonMap("db_name", dbname));



running with -Ddb_name=db1

getDBHost() == "db1"
getDBName() == "testdb"
getDBUser() == "testuser"
getDBPass() == "verysecret"

running with -Ddb_name=db2

getDBHost() == "db2"
getDBName() == "large_testdb"
getDBUser() == "testuser"
getDBPass() == "verysecret"

running with -Ddb_name=db3

getDBHost() == "db3"
getDBName() == "testdb"
getDBUser() == "testsuer"
getDBPass() == "verysecret"

anything else:

getDBHost() == "localhost"
getDBName() == "testdb"
getDBUser() == "testuser"
getDBPass() == "verysecret"


If @Default() annotations are added to the fields, their value is only
used if no property in the @Config() annotation exists.









Reply all
Reply to author
Forward
0 new messages