java - Spring Boot application.properties 生命周期

标签 java spring spring-boot application.properties

我有一个大型 Spring Web 应用程序,可以追溯到几年前。我需要将其更新为 Spring Boot(公司要求)。我进展顺利 - 它开始了(!),尽管注入(inject)的属性存在一些问题,这会导致应用程序失败。

具体来说,每个配置文件有三个巨大的配置文件,例如qa_config.propertiesqa_ehcache.xmlqa_monitoring.properties。目前我只关心 qa_config.properties,我已将其重命名为 Spring Boot 的首选名称 application-qa.propertiesapplication-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.propertiesapplication-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/

相关文章:

java - 没有临时队列的 JMS RPC

java - 如何使用@AutoConfigureMockMvc仅打印失败测试的请求?

spring - 如何在 Spring Web MVC 中为所有 @RestController 设置上下文根?

flutter - 如何在 Flutter Web 前端应用程序和 SpringBoot REST API 中实现 SAML?

java - 仅在保存实体时制作 transient 列

java - 如何触发@LastModifiedDate

java - 如何在不打开的情况下保存 itextpdf 生成的 pdf 文件?

java - 从 Spring 支架 Controller 返回带有查询参数的响应

java - Firebase 身份验证错误 getGoogleApiForMethod() 返回 Gms :

java - 如何存储具有可变数量属性的java对象