試用配置管理庫typesafe.config
試用配置管理庫typesafe.config
Typesafe的Config庫,純Java寫成、零外部依賴、代碼精簡、功能靈活、API友好。支持Java properties、JSON、JSON超集格式HOCON以及環境變量。它也是Akka的配置管理庫.
Overview
- 純java實現,無任何依賴
- 充分的測試
- 支持: Java properties, JSON, and a human-friendly JSON superset
- 可以合並各種格式的配置文件
- 可以通過文件、urls、classpath加載配置
- 支持多層嵌套的配置方式
- 識別Java system properties, 如
java -Dmyapp.foo.bar=10
- 可以轉換長短,大小等單位。如配置文件中
timeout=10s
,則可以轉換成任意的毫秒或者 - 類型轉換,比如yes可以轉換為boolean類型的true
- 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 (logdir=${HOME}/logs)
目前config隻支持配置文件,如果想從數據庫獲取配置文件,需要自己diy。 config庫很擅長合並配置。
Example
默認加載classpath下的application.conf,application.json和application.properties文件。通過ConfigFactory.load()加載。
# these are our own config values defined by the app
simple-app {
answer=42
}
# Here we override some values used by a library
simple-lib.foo="This value comes from simple-app's application.conf"
simple-lib.whatever = "This value comes from simple-app's application.conf"
public class SimpleLibContext {
private Config config;
//指定配置文件
public SimpleLibContext(Config config) {
this.config = config;
config.checkValid(ConfigFactory.defaultReference(), "simple-lib");
}
// 默認加載classpath下的application.*
public SimpleLibContext() {
this(ConfigFactory.load());
}
//打印
public void printSetting(String path) {
System.out.println("The setting '" + path + "' is: " + config.getString(path));
}
public static void main(String[] args) {
SimpleLibContext s = new SimpleLibContext();
s.printSetting("simple-app.answer");
}
}
Reference
https://stackoverflow.com/questions/18668883/using-typesafes-config-to-manage-my-database-connection
https://github.com/typesafehub/config/tree/master/examples
https://github.com/typesafehub/config
最後更新:2017-04-03 12:56:29