详解Spring Boot 自定义PropertySourceLoader
SpringBoot的配置文件内置支持properties、xml、yml、yaml几种格式,其中properties和xml对应的Loader类为PropertiesPropertySourceLoader,yml和yaml对应的Loader类为YamlPropertySourceLoader。
观察这2个类可以发现,都实现自接口PropertySourceLoader。所以我们要新增支持别的格式的配置文件,就可以通过实现接口PropertySourceLoader来实现了。
下面实现了一个json格式的配置文件Loader类:
packagecom.shanhy.sboot.property;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.HashMap;
importjava.util.LinkedList;
importjava.util.List;
importjava.util.Map;
importorg.springframework.boot.env.PropertySourceLoader;
importorg.springframework.boot.json.JsonParser;
importorg.springframework.boot.json.JsonParserFactory;
importorg.springframework.core.env.MapPropertySource;
importorg.springframework.core.env.PropertySource;
importorg.springframework.core.io.Resource;
/**
*JSON格式配置文件加载器
*
*@author单红宇(CSDNCATOOP)
*@create2017年4月20日
*/
publicclassJsonPropertySourceLoaderimplementsPropertySourceLoader{
publicString[]getFileExtensions(){
//配置文件格式(扩展名)
returnnewString[]{"json"};
}
publicPropertySource>load(Stringname,Resourceresource,Stringprofile)throwsIOException{
//处理机制参考PropertiesPropertySourceLoader
//无论profile有没有值,底层都会尝试先执行load(Stringname,Resourceresource,null),所以这个地方之间判断等于null即可。
//当前版本springboot-1.5.2(后续版本未知)详见ConfigFileApplicationListener的445行
if(profile==null){
Mapresult=mapPropertySource(resource);
returnnewMapPropertySource(name,result);
}
returnnull;
}
/**
*解析Resource为Map
*
*@paramresource
*@return
*@throwsIOException
*
*@author单红宇(CSDNCATOOP)
*@create2017年4月20日
*/
privateMapmapPropertySource(Resourceresource)throwsIOException{
if(resource==null){
returnnull;
}
Mapresult=newHashMap();
JsonParserparser=JsonParserFactory.getJsonParser();
Mapmap=parser.parseMap(readFile(resource));
nestMap("",result,map);
returnresult;
}
/**
*读取Resource文件内容为字符串
*
*@paramresource
*@return
*@throwsIOException
*
*@author单红宇(CSDNCATOOP)
*@create2017年4月20日
*/
privateStringreadFile(Resourceresource)throwsIOException{
InputStreaminputStream=resource.getInputStream();
ListbyteList=newLinkedList();
byte[]readByte=newbyte[1024];
intlength;
while((length=inputStream.read(readByte))>0){
for(inti=0;iresult,Mapmap){
if(prefix.length()>0){
prefix+=".";
}
for(Map.EntryentrySet:map.entrySet()){
if(entrySet.getValue()instanceofMap){
nestMap(prefix+entrySet.getKey(),result,(Map)entrySet.getValue());
}else{
result.put(prefix+entrySet.getKey().toString(),entrySet.getValue());
}
}
}
}
然后在src/main/resources中创建META-INF/spring.factories文件,内容为:
org.springframework.boot.env.PropertySourceLoader=\ com.shanhy.sboot.property.JsonPropertySourceLoader
创建测试的配置文件application.json
{
"custom":{
"property":{
"message":"测试数据"
}
}
}
创建验证结果的HelloController.Java
@RestController
publicclassHelloController{
@Value("${custom.property.message:}")
privateStringcustomProperty;
@RequestMapping("/test")
publicStringtest(){
returncustomProperty;
}
}
启动工程服务,浏览器访问http://localhost:8080/test即可查看输出的结果为“测试数据”;
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。