1. 程式人生 > >spring boot 讀取自定義properties檔案

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檔案路徑