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了!!!