Spring Boot1.4版本后@ConfigurationProperties注解舍弃location参数后的解决方式

xiaoxiao2021-02-28  79

之前可以通过这样的方式来实现Bean和自定义配置文件的关联

@Component //可以使用locations指定读取的properties文件路径,如果不指定locations就会读取默认的properties配置文件 @ConfigurationProperties(prefix = "author",location="classpath:author.properties") public class AuthorSettings { private String name; private Long age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getAge() { return age; } public void setAge(Long age) { this.age = age; } } 但是Spring Boot在1.4版本后舍弃了@ConfigurationProperties注解的location参数,导致不能自定义配置文件的位置,用起来比较麻烦。

官方给的解释是为了鼓励大家多使用Environment

按照官方的意思,重新换种方式实现加载自定义配置文件(依然比较麻烦)

新建一个类,监听ApplicationEnvironmentPreparedEvent事件,通过ResourceLoader加载自定义的配置文件

public class LoadAdditionalProperties implements ApplicationListener<ApplicationEnvironmentPreparedEvent> { private ResourceLoader loader = new DefaultResourceLoader(); @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent applicationEnvironmentPreparedEvent) { try { Resource resource = loader.getResource("classpath:author.properties"); PropertySource<?> propertySource = new PropertySourcesLoader().load(resource); applicationEnvironmentPreparedEvent.getEnvironment().getPropertySources().addLast(propertySource); }catch(IOException e){ throw new IllegalStateException(e); } } } 然后在main方法类中

@RestController @SpringBootApplication public class Ch623Application { // @Autowired // private DemoConfig demoConfig; @Autowired private Environment env; @RequestMapping("/") public String index() { return env.getProperty("author.age"); } public static void main(String[] args) { new SpringApplicationBuilder(Ch623Application.class) .listeners(new LoadAdditionalProperties()) .run(args); } }

最后附上配置文件author.properties author.name=magicnian author.age=25

访问http://localhost:8080/即可看到结果

参考:https://github.com/spring-projects/spring-boot/issues/6220#issuecomment-228412077

转载请注明原文地址: https://www.6miu.com/read-26738.html

最新回复(0)