SpringBoot + @RefreshScope:动态刷新配置

步骤1 添加必要依赖

<!-- pom.xml -->
<dependencies>
    <!-- Spring Boot基础依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- 配置刷新核心 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    
    <!-- 配置中心支持 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter</artifactId>
        <version>3.1.3</version>
    </dependency>
</dependencies>

步骤2:启用刷新机制

// 主应用类
@SpringBootApplication
@EnableRefreshScope  // 关键注解:开启配置刷新能力
public class DynamicConfigApp {
    public static void main(String[] args) {
        SpringApplication.run(DynamicConfigApp.class, args);
    }
}

 

步骤3:配置application.yml

# 应用基础配置
app:
feature:
    enabled:true
    timeout:5000
    retry-count:3
    welcome-msg:"Hello, Dynamic Config!"

# 暴露刷新端点(关键!)
management:
endpoints:
    web:
      exposure:
        include: refresh,health,info

 

步骤4:创建动态配置Bean

@Service
@RefreshScope// 标记此Bean支持动态刷新
publicclassFeatureService {
    
    // 注入可刷新的配置项
    @Value("${app.feature.enabled}")
    privateboolean featureEnabled;
    
    @Value("${app.feature.timeout}")
    privateint timeout;
    
    @Value("${app.feature.retry-count}")
    privateint retryCount;
    
    @Value("${app.feature.welcome-msg}")
    private String welcomeMessage;

    public String getFeatureConfig() {
        return String.format("""
            Feature Enabled: %s
            Timeout: %d ms
            Retry Count: %d
            Message: %s
            """, featureEnabled, timeout, retryCount, welcomeMessage);
    }
}

 

深入理解@RefreshScope

1. 作用域代理原理

// 伪代码:Spring如何实现动态刷新
publicclassRefreshScopeProxyimplementsApplicationContextAware {
    private Object targetBean;
    
    @Override
    public Object invoke(Method method) {
        if (configChanged) {
            // 1. 销毁旧Bean
            context.destroyBean(targetBean);
            // 2. 重新创建Bean
            targetBean = context.getBean(beanName);
        }
        return method.invoke(targetBean, args);
    }
}

2. 刷新范围控制技巧

场景1:只刷新特定Bean的部分属性

@Component
@RefreshScope
publicclassPaymentService {
    // 只有带@Value的属性会刷新
    @Value("${payment.timeout}")
    privateint timeout;
    
    // 不会被刷新的属性
    privatefinalStringapiVersion="v1.0"
}

场景2:组合配置类刷新

@Configuration
@RefreshScope// 整个配置类可刷新
publicclassAppConfig {
    
    @Bean
    @RefreshScope
    public FeatureService featureService() {
        returnnewFeatureService();
    }
    
    @Value("${app.theme}")
    private String theme;
}
posted @ 2025-09-03 22:26  KLAPT  阅读(63)  评论(0)    收藏  举报