如何在Spring Boot启动后运行时无需重启加载配置属性
解决Spring Boot配置动态刷新问题
首先明确:@ConditionOnProperty是应用启动阶段的条件判断注解,只会在Bean初始化时执行一次判断逻辑,运行时修改配置根本触发不了它的更新,所以你必须重启才能生效是正常现象。要实现配置动态刷新,得用Spring Cloud的@RefreshScope或者Spring Boot原生的配置绑定+刷新机制,下面给具体可行方案:
方案1:@Value + @RefreshScope(单个配置项场景)
如果只是需要动态获取单个配置值,直接在读取配置的类上添加@RefreshScope,配合@Value注解即可:
import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Component; @Component @RefreshScope public class AgeHolder { @Value("${spring.age}") private Integer age; public Integer getAge() { return age; } }
修改application.properties里的spring.age=20后,发送POST请求到/actuator/refresh端点就能触发配置刷新。
需要提前做两个准备:
- 引入spring-cloud-starter-bootstrap依赖(Spring Cloud 2020+版本)
- 在配置文件中开启actuator端点:
management.endpoints.web.exposure.include=refresh
方案2:@ConfigurationProperties + @RefreshScope(批量配置场景)
如果有多个配置项需要动态刷新,用@ConfigurationProperties做批量绑定更规范,同样搭配@RefreshScope:
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Component; @Component @RefreshScope @ConfigurationProperties(prefix = "spring") public class AppConfig { private Integer age; // 必须提供getter、setter方法 public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
修改配置后调用/actuator/refresh,就能刷新所有绑定的配置值。
动态切换Bean实现(替代@ConditionOnProperty的动态生效)
如果你的需求是根据spring.age的动态值切换不同的Bean实现,光刷新配置还不够,得结合@RefreshScope和实时判断逻辑:
@RefreshScope @Component public class AgeServiceProvider { @Autowired private AppConfig appConfig; public AgeService getCurrentAgeService() { if (appConfig.getAge() >= 20) { return new AdultAgeService(); } else { return new MinorAgeService(); } } } // 定义服务接口和不同实现 interface AgeService { String getAgeDescription(); } class AdultAgeService implements AgeService { @Override public String getAgeDescription() { return "成年人"; } } class MinorAgeService implements AgeService { @Override public String getAgeDescription() { return "未成年人"; } }
这样每次调用getCurrentAgeService()时,都会根据最新的配置值返回对应的Bean实现,无需重启应用。
注意事项
- 若不依赖Spring Cloud,Spring Boot 2.4+可通过
spring.config.import实现原生配置刷新,但@RefreshScope仍是最简便的方案。 - 只有标注了
@RefreshScope的Bean会触发动态刷新,普通Bean不会自动更新配置。
内容的提问来源于stack exchange,提问作者Farid Khan
相关产品推荐
相关产品推荐

