Java @具有不同*.properties文件的RefreshScope
我想在调用刷新端点时重新加载多个配置文件。它可以很好地处理application.properties文件中的条目。任何其他文件都不会刷新 这里有一个小例子: pom.xmlJava @具有不同*.properties文件的RefreshScope,java,spring,spring-cloud,spring-cloud-config,Java,Spring,Spring Cloud,Spring Cloud Config,我想在调用刷新端点时重新加载多个配置文件。它可以很好地处理application.properties文件中的条目。任何其他文件都不会刷新 这里有一个小例子: pom.xml ... <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web&
...
<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>
...
测试属性
greeting=Hi
management.endpoints.web.exposure.include=refresh
test=Test
配置文件持有者1
@Repository
@PropertySource(value="application.properties")
@RefreshScope
public class ConfigFileHolder1 {
@Value("${greeting}")
private String greeting;
public String getGreeting() {
return greeting;
}
}
配置文件持有者2
@Repository
@PropertySource(value="test.properties")
@RefreshScope
public class ConfigFileHolder2 {
@Value("${test}")
private String test;
public String getTest() {
return test;
}
}
高级控制器
@Controller
@RefreshScope
public class ApiController implements Api {
@Autowired
private ConfigFileHolder1 config1;
@Autowired
private ConfigFileHolder2 config2;
// do something with config1 and config2
...
}
调用刷新端点后,只有ConfigFileHolder1将刷新其值。要刷新ConfigFileHolder2的值,应用程序必须重新启动
刷新所有配置文件/ConfigFileHolder的值需要更改什么
感谢您的帮助。刷新范围
@RefreshScope
将仅适用于Spring Boot加载的属性,而不适用于该过程稍后加载的@PropertySource
s。因此,您需要告诉Spring Boot加载附加的
您可以通过添加名称(spring.config.name
)或位置spring.config.additional location
来实现这一点
指定其他名称时,请确保包括默认的应用程序
,以及不再加载的其他应用程序
--spring.config.name=application,test
当指定上述作为参数时,将检查所有位置的应用程序.properties
和测试.properties
以及配置文件的扩展
--spring.config.additional-location=classpath:test.properties
这将仅从类路径加载
test.properties
,并且在运行时或多或少不可能更改文件,但文件将从该确切位置加载。不会应用配置文件扩展。它似乎会刷新,因为它“加载”了默认文件的应用程序.properties
,该文件将自动重新加载。要重新加载的文件是Spring Boot自动加载的默认文件。您应该通过test.properties
测试才能访问该文件列表。您知道怎么做吗?在问我的问题之前,我试图搜索类似的东西,但没有找到任何有用的东西。使用spring.config.location
或spring.config.additional location
,传入要加载的文件名。我在运行配置参数中添加了--spring.config.additional location=classpath:test.properties,效果很好。谢谢你的帮助。如果你想让我接受你的答案,请留下真实的答案,而不仅仅是评论。
--spring.config.additional-location=classpath:test.properties