精选
推荐文章

springboot+apollo的热更新的详细方案

mini云码 发布日期: 2025-11-05 09:02


apollo本身是支持热更新的,在apollo上修改了配置,客户端假如是用@Vaule获取的,是可以感知到热更新的。也就是说在apollo的管理控制台上修改了配置,在连接了这个apollo的客户端应用上,访问带@Value属性的字段的时候是能获取到最新数据的。

但有两种情况除外,

情况一:使用ConfigurationProperties注解的配置类.

这种配置类,不是通过@Vaule设置属性的,只会在初始化的时候读取一次apollo配置。当apollo配置变化的时候,类的属性不会自动刷新。

这时候,使用@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 = "myobj.test")
public class TestProperties {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}


情况二:@Value间接引用了另外一个配置

比如@Value("${xx.abc}")

而在apollo上面的配置是这样的:

xx.abc=${name}
name=xiaoming

因此,@Value的值其实是指向name这个配置的

当name的值发生改变的时候,假如单纯使用@Value注解标注这个属性,是不会自动热刷新的,因为在springboot看来,xx.abc的值没有改变。

这时候,在引用@Value这个注解所在的类,加一个@RefreshScope的注解就能解决这个问题。代码例子:

@Service
@RefreshScope
piblic class TestService(
    @Value("${xx.abc}")
    String abc;
)