在Spring MVC中,如果你想在运行时更改属性值而不重启应用服务器,可以使用Spring的@Value
注解结合Environment
接口,或者使用Spring Cloud Config来实现动态刷新配置。
Spring的@Value
注解:这个注解用于注入属性值到Spring管理的bean中。
Spring的Environment
接口:提供了访问应用程序环境属性的方法。
Spring Cloud Config:一个集中式的配置管理服务,支持配置的外部化和动态刷新。
@RefreshScope
注解。@RefreshScope
进行本地配置刷新<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
@RefreshScope
注解:import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class ConfigController {
@Value("${example.property}")
private String exampleProperty;
@GetMapping("/property")
public String getProperty() {
return exampleProperty;
}
}
/actuator/refresh
端点来刷新配置:curl -X POST http://localhost:8080/actuator/refresh
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
bootstrap.yml
中配置Config Server的地址:spring:
cloud:
config:
uri: http://localhost:8888
@RefreshScope
注解在需要动态刷新的bean上。/actuator/refresh
端点。问题:配置刷新后没有生效。
原因:
@RefreshScope
注解。refresh
端点没有被正确激活。解决方法:
@RefreshScope
注解。management.endpoints.web.exposure.include
包含了refresh
。management:
endpoints:
web:
exposure:
include: refresh, health, info
通过上述方法,你可以在Spring MVC应用中实现配置的动态刷新,从而提高开发和运维效率。
领取专属 10元无门槛券
手把手带您无忧上云