Henning Schmiedehausen
unread,Nov 28, 2010, 3:05:17 PM11/28/10Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to config-magic
Coercing Configuration objects out of properties
================================================
Coercing objects out of property values has been enhanced and made
configurable in 0.6.
The following types are builtin:
- Boolean, Byte, Short, Integer, Long, Float, Double and String
- URI is constructed using URI.create(String) (new in 0.6)
In addition, there are now fallback coercion for arbitrary types if
they adhere to one of these rules:
- has a 'public static T valueOf(String)' method
- has a 'public T(String)' constructor
- has a 'public T(Object)' constructor (that accepts a String as a
valid object)
Registering custom code for type coercion
-----------------------------------------
Any custom coercing code is run after the builtin converters and
before the fallback code.
It is not possible to override a builtin coercer; if custom code is
registered for any of the builtin types, it has no effect.
Custom type conversion must implement two interfaces:
public interface Coercible<T>
{
Coercer<T> accept(Class<?> clazz);
}
decides to accept a type or not. If it accepts a type, it returns a
Coercer to convert a String into the type, otherwise null.
public interface Coercer<T>
{
T coerce(String value);
}
does the actual conversion.
Example:
Config Bean:
public interface WibbleConfig
{
@Config("the-value")
Wibble getWibble();
}
Type:
public class Wibble
{
private String value = null;
public void setValue(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
Custom converter:
public class WibbleCoercible implements Coercible<Wibble>
{
public Coercer<Wibble> accept(final Class<?> clazz)
{
if (Wibble.class.equals(clazz)) {
return new Coercer<Wibble>() {
public Wibble coerce(final String value) {
Wibble w = new Wibble();
w.setValue(value);
return w;
}
};
}
return null;
}
}
Register the converter with the ConfigurationObjectFactory:
ConfigurationObjectFactory c = new
ConfigurationObjectFactory(System.getProperties());
c.addCoercible(new WibbleCoercible();
WibbleConfig wibbleConfig = c.build(WibbleConfig.class);
String value = wibbleConfig.getWibble().getValue();
Custom converters are most useful for types that have various ways to
interpret a string value, e.g. JodaTime DateTime objects.