我有一个大型 Spring Web 应用程序,可以追溯到几年前。我需要将其更新为 Spring Boot(公司要求)。我进展顺利 - 它开始了(!),尽管注入(inject)的属性存在一些问题,这会导致应用程序失败。
具体来说,每个配置文件有三个巨大的配置文件,例如qa_config.properties
、qa_ehcache.xml
、qa_monitoring.properties
。目前我只关心 qa_config.properties
,我已将其重命名为 Spring Boot 的首选名称 application-qa.properties
和 application-qa_monitoring.properties
该应用程序有许多用 @Named
(来自 javax.ws.rs-api )注释的类,这些类是提前加载的 - 太早了,我需要在构造函数中注入(inject)属性:
package com.domain.app;
import org.springframework.beans.factory.annotation.Value;
import javax.inject.Named;
@Named
public class Foo {
// Cant use @Value here, it is not yet in the context
protected String bar; // lives in application-qa.properties
protected String qux; // lives in application-qa_monitoring.properties
public Foo(@Value("${application.property.named.bar}") String bar,
@Value("${monitoring.property.named.qux}") String qux) {
this.bar = bar;
this.qux = qux;
doSomeWork();
}
}
属性文件:
#application-qa.properties
application.property.named.bar=something
和
#application-qa_monitoring.properties
monitoring.property.named.qux=another_thing
我的问题:我希望尽快将 application-qa.properties
和 application-qa_monitoring.properties
放入上下文中,之前 @Named
类已加载。
为了实现这一目标,我使用 qa
的 Activity 配置文件运行应用程序,该配置文件成功地将这组属性添加到上下文中。
我将此行添加到 application.properties
文件中,以确保加载其他属性:
spring.profiles.include=${spring.profiles.active}_monitoring.properties
当我运行 Spring Boot 应用程序时,输出告诉我
The following profiles are active: qa_monitoring.properties,qa
调试Foo
类时,bar
的值是正确的
但是,qux
的值为 null。
我是否遗漏了有关属性文件加载顺序的信息?我本以为 application.properties
中的 include
行足以很早就“展平”这两个文件(如果一个文件在上下文中),所以两个文件都应该是可用吗?
我可以做的就是将两个属性文件中的所有变量放入一个 application-qa.properties 中,但如果可能的话,我希望将它们分开并作为尽可能接近原始结构。
最佳答案
感谢 pvpkiran 和安迪·布朗。
我的 application.properties 文件应该已读取
spring.profiles.include=${spring.profiles.active}_monitoring
即,只需添加另一个配置文件
,在本例中为qa_monitoring
- Spring自动添加application-
前缀和.properties后缀
关于java - Spring Boot application.properties 生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49514691/