描述
properties文件的配置工具库,配置修改动态生效。支持扫描本地目录/git/svn仓库。
使用方法
配置类
定义配置类
配置文件:demo.properties
demo.attrStr=strValue
demo.attrLong=10000
demo.attrInt=100
demo.attrBool=true
配置类:DemoConf.java
@Config(file = "demo.properties", prefix = "demo")
public class DemoConf implements Conf {
private static transient final Logger LOG = LoggerFactory.getLogger(Conf.class);
public final static DemoConf ME = new DemoConf();
static {
try {
ConfKit.handler(DemoConf.class);
} catch (Exception e) {
LOG.error("handler DemoConf failed.", e);
}
}
String attrStr;
long attrLong;
int attrInt;
boolean attrBool;
//省略getter/setter方法
@Override
public String toString() {
return "DemoConf [attrStr=" + attrStr + ", attrLong=" + attrLong + ", attrInt=" + attrInt + ", attrBool="
+ attrBool + "]";
}
}
调用配置类对象
public class Main {
public static void main(String[] args) throws InterruptedException {
// 通过配置类的me获取实例调用配置属性
System.out.println(DemoConf.ME);
// 通过ConfigManager.config(配置类)获取实例调用配置属性
System.out.println(ConfigManager.config(DemoConf.class));
// 通过ConfigManager.putProperties()追加自定义全局配置属性
Properties properties = new Properties();
String testPropertyKey = "test.add.property.key";
properties.setProperty(testPropertyKey, "test.add.property.value");
ConfigManager.putProperties(properties);
System.out.println(testPropertyKey + "=" + ConfigManager.getValueByKey(testPropertyKey));
}
}
控制台输出
DemoConf [attrStr=strValue, attrLong=10000, attrInt=100, attrBool=true]
DemoConf [attrStr=strValue, attrLong=10000, attrInt=100, attrBool=true]
test.add.property.key=test.add.property.value
配置扫描器
配置扫描器配置
conf4j.properties
##conf4j config扫描器配置
#扫描器类
conf4j.config.scaner.className=com.conf4j.file.scaner.ConfigFileScaner
conf4j.config.scaner.url=
conf4j.config.scaner.user=
conf4j.config.scaner.password=
#扫描的本地配置目录,可使用绝对路径,也支持相对路径
conf4j.config.scaner.localPath=src/test/resources1
#扫描配置的间隔(秒)
conf4j.config.scaner.intervalSec=2
#扫描的配置文件,多个文件以','分割
conf4j.config.scaner.keys=conf4j.properties,demo.properties
启动配置扫描器
public class Main {
public static void main(String[] args) throws InterruptedException {
//启动配置扫描
ConfigManager.startScaner();
int i = 0;
while (i++ < 100) {
Thread.sleep(2000);
System.out.println(DemoConf.ME);
}
}
}
控制台输出
DemoConf [attrStr=strValue, attrLong=10000, attrInt=100, attrBool=true]
DemoConf [attrStr=strValue, attrLong=10000, attrInt=100, attrBool=true]
...
工程介绍
- conf4j.api支持扫描本地配置目录
- conf4j.git支持扫描git仓库
- conf4j.svn支持扫描svn仓库
例子参考conf4j.api/conf4j.git/conf4j.svn中的Main类
-D参数使用
-D参数或conf4j.properties中conf4j.config.scaner.localPath不为空时,配置路径中配置文件覆盖类路径下的配置文件
-Dconf4j.config.scaner.localPath=config/local/path
扩展使用
可以扫描类根据Config注解对配置类自动注入属性,省去static代码块中ConfKit.handle方法的调用。
约束
自己读取配置文件请使用com.conf4j.kit.ClassLoaderKit.getResourceAsStream(String)接口