主要解决的问题描述:
在springboot项目中,静态工具类无法使用@Value来自动注入配置文件的值,但是工具类中会需要读取配置的情况
解决方案:
private static String ClassPathResource = "application.yml";
WritableResource writableResource = new PathResource("./" + PROPERTY_NAME);
if (!writableResource.exists()) {
Resource resource = new ClassPathResource(PROPERTY_NAME);
yamlFactory.setResources(resource);
} else {
yamlFactory.setResources(writableResource);
}
Properties configProperties = yamlFactory.getObject();
由于经常性我们会把application.yml文件抽离到jar包外部,使用ClassPathResource读取不到文件,优先通过PathResource读取jar包外部的配置文件,若读取不到再通过ClassPathResource来获取src/main/resources下的application.yml文件,如有更简便优雅方式,欢迎留言!