码迷,mamicode.com
首页 > 编程语言 > 详细

spring boot 读取自定义properties文件

时间:2018-11-09 16:14:45      阅读:380      评论:0      收藏:0      [点我收藏+]

标签:文件路径   cep   nal   control   ash   one   def   ops   coding   

@Configuration
@Component
public class PropertiesConfig {

private static final String[] properties = {"/application.properties"};
private static Properties props;
private static Map<Object, Object> propertiesMap = new HashMap();

public PropertiesConfig() {
try {
for (String propertie : properties) {
Resource resource = new ClassPathResource(propertie);
if(null != resource && resource.exists()){
EncodedResource encodeResource = new EncodedResource(resource, DEFAULT_ENCODING);
props = PropertiesLoaderUtils.loadProperties(encodeResource);
propertiesMap.putAll(props);
}
}
if(null != propertiesMap){
props.clear();
for (Map.Entry<Object, Object> item : propertiesMap.entrySet()) {
if(!StringUtils.isEmpty(item.getKey())){
props.setProperty(item.getKey().toString(),StringUtils.isEmpty(item.getValue()) ? "" : item.getValue().toString());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

public static String getProperty(String key) {
return props == null ? null : props.getProperty(key);

}

说明:
@Configuration项目启动时加载
@component (把普通pojo实例化到spring容器中,相当于配置文件中的 <bean id="" class=""/>)泛指各种组件,就是说当我们的类不属于各种归类的时候(不属于@Controller、@Services等的时候),我们就可以使用@Component来标注这个类。
properties 为读取的peoperties文件集合
使用:
@Autowired
private PropertiesConfig propertiesConfig;

propertiesConfig.getProperty(key);

***暂时未找到获取所有properties文件路径
 

 






spring boot 读取自定义properties文件

标签:文件路径   cep   nal   control   ash   one   def   ops   coding   

原文地址:https://www.cnblogs.com/Mr-xt/p/9935004.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!