@RefreshScope具有不同的* .properties文件

问题描述

我想在调用刷新端点时重新加载多个配置文件。它与application.properties文件中的条目完美配合。其他任何文件都不会刷新。

这里有个小例子:

pom.xml

...
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.3.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
        <version>2.3.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter</artifactId>
        <version>2.2.4.RELEASE</version>
    </dependency>
</dependencies>
...

application.properties

greeting=Hi
management.endpoints.web.exposure.include=refresh

test.properties

test=Test

ConfigFileHolder1

@Repository
@PropertySource(value="application.properties")
@RefreshScope
public class ConfigFileHolder1 {
    @Value("${greeting}")
    private String greeting;
    
    public String getGreeting() {
        return greeting;
    }
}

ConfigFileHolder2

@Repository
@PropertySource(value="test.properties")
@RefreshScope
public class ConfigFileHolder2 {
    
    @Value("${test}")
    private String test;
    
    public String gettest() {
        return test;
    }
}

ApiController

@Controller
@RefreshScope
public class ApiController implements Api {

    @Autowired
    private ConfigFileHolder1 config1;
    
    @Autowired
    private ConfigFileHolder2 config2;

   // do something with config1 and config2
   ...
}

调用刷新端点之后,只有ConfigFileHolder1会刷新其值。要刷新ConfigFileHolder2的值,必须重新启动应用程序。

要刷新所有config-files / ConfigFileHolder的值,我需要更改什么?

感谢您的帮助。

解决方法

@RefreshScope仅适用于Spring Boot加载的属性,不适用于稍后在过程中加载的@PropertySource。因此,您将需要告诉Spring Boot加载额外的configuration files

您可以通过添加名称(spring.config.name)或位置spring.config.additional-location来做到这一点。

指定其他名称时,请确保包括默认的application以及其他将不再加载的名称。

--spring.config.name=application,test

在将以上内容指定为参数时,将同时检查application.propertiestest.properties的所有位置,并应用配置文件扩展名。

--spring.config.additional-location=classpath:test.properties

这只会从类路径中加载test.properties,这将或多或少地在运行时更改文件,但是将从该确切位置加载文件。不会应用任何个人资料扩展。