springBoot是個很方便的工具,相對於以前的springMVC,寫起來節省了不少時間!
springBoot讀取配置文件的方式很多,可以使用 @Value("${druid.type}")的方式去讀取
也可以使用 @ConfigurationProperties(prefix = "druid.master")在實體類裏面獲取配置文件的信息,
但是這兩種方式都有個問題,對於用static修飾的屬性,無效。而我們平時工具類裏面都是會聲明很多static的屬性的,這裏給大家推薦一種方法,親身試過,很不錯很好用...
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
/**
* 獲取配置文件裏面的內容
* @param key 屬性的key值
* @param proName 配置文件的名稱
* @return
*/
public static Object getCommonYml(String key,String proName){
Resource resource = new ClassPathResource(proName);
Properties properties = null;
try {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setResources(resource);
properties = yamlFactory.getObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return properties.get(key);
}
然後
public static void main(String[] args) {
System.out.println(getCommonYml("druid.type","application.yml"));
}
這樣就沒那麼麻煩了,想取用那個字段就把對應字段的key值帶進去就OK了!!!