汎用的に使えそうなのでメモ。
public class ConfigurationFactory {private static final String FILENAME = "xxxxx.properties";
private static Configuration singleton = null;
public static Configuration getConfiguration() {
if (singleton == null)
initializeConfiguration();return singleton;
}public static void initializeConfiguration() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();if (loader == null)
loader = ConfigurationFactory.class.getClassLoader();final Properties props = new Properties();
InputStream in = loader.getResourceAsStream(FILENAME);if (in != null) {
try {
try {
props.load(in);
} finally {
in.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}Class interfaces = { Configuration.class };
singleton = (Configuration) Proxy.newProxyInstance(loader, interfaces, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object args) throws Throwable {
String name = method.getName();if ("toString".equals(name))
return props.toString();if (!(name.startsWith("get") || name.startsWith("set")) || name.length() < 4)
return null;String prefix = name.substring(0, 3);
String key = name.substring(3).replaceAll("(\\p{Upper}+)", ".$1").replaceAll("^\\.", "").toLowerCase();if ("get".equals(prefix)) {
String value = props.getProperty(key);
return StringUtils.isNotBlank(value) ? value : null;
} else {
props.setProperty(key, (String) args[0]);
return null;
}
}
});
}}
public interface Configuration {// get/setAaaBbb() -> aaa.bbb = XXXXX
}