无Config Server与Actuator下Spring Boot本地配置刷新方案咨询
实现方案
完全可以不依赖Actuator和Config Server实现自定义配置刷新,以下是两种可选实现方式:
方式一:轻量依赖Spring Cloud Context实现(代码量最少)
仅需引入极轻量的spring-cloud-context依赖,无需其他多余组件:
- 首先补全配置类的getter、setter方法,Spring配置绑定依赖setter完成:
@ConfigurationProperties("myapp.sample") public class Prop{ private int prop1; private int prop2; public int getProp1() { return prop1; } public void setProp1(int prop1) { this.prop1 = prop1; } public int getProp2() { return prop2; } public void setProp2(int prop2) { this.prop2 = prop2; } }
- 给配置类添加
@RefreshScope注解,标记该Bean支持动态刷新:
你可以直接在配置类上添加注解并注册为Bean:
@RefreshScope @Component @ConfigurationProperties("myapp.sample") public class Prop{ // 属性和getter、setter同上 }
- 编写自定义
/reload接口,触发配置刷新:
import org.springframework.cloud.context.refresh.ContextRefresher; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class CustomReloadController { private final ContextRefresher contextRefresher; public CustomReloadController(ContextRefresher contextRefresher) { this.contextRefresher = contextRefresher; } @PostMapping("/reload") public String reloadConfig() { // 该方法会自动重新加载环境配置、刷新所有@RefreshScope标注的Bean contextRefresher.refresh(); return "配置刷新完成"; } }
方式二:零额外依赖手动实现
如果你完全不想引入任何第三方额外依赖,可以手动实现配置读取、实例替换逻辑:
- 编写配置持有类,负责配置的加载和持有:
import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; @Component public class PropHolder { // 用volatile保证多线程下的可见性 private volatile Prop currentProp; public Prop getCurrentProp() { return currentProp; } @PostConstruct public void init() throws IOException { // 项目启动时先加载一次配置 doReload(); } public void doReload() throws IOException { Properties properties = new Properties(); // 替换为你的本地配置文件实际路径 try (InputStream inputStream = new FileInputStream("/opt/config/myapp.properties")) { properties.load(inputStream); } Prop newProp = new Prop(); newProp.setProp1(Integer.parseInt(properties.getProperty("myapp.sample.prop1"))); newProp.setProp2(Integer.parseInt(properties.getProperty("myapp.sample.prop2"))); // 替换为新的配置实例 this.currentProp = newProp; } }
- 编写自定义
/reload接口:
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RestController public class CustomReloadController { private final PropHolder propHolder; public CustomReloadController(PropHolder propHolder) { this.propHolder = propHolder; } @PostMapping("/reload") public String reloadConfig() throws IOException { propHolder.doReload(); return "配置刷新完成"; } }
- 使用时直接注入
PropHolder,调用getCurrentProp()即可拿到最新的配置值。
注意事项
- 方式一的
spring-cloud-context依赖仅提供基础的上下文刷新能力,不会引入Config Server、Actuator等其他组件,体积非常小 - 方式二需要自行处理配置读取路径、类型转换异常、编码兼容等边界问题,适合对依赖体积有极致要求的场景
内容的提问来源于stack exchange,提问作者RamPrakash
相关产品推荐
相关产品推荐

