spring boot 读取自定义properties文件

@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文件路径
 

 






猜你喜欢

转载自www.cnblogs.com/Mr-xt/p/9935004.html