apollo

关于apollo刷新带有@ConfigurationProper

2021-10-30  本文已影响0人  virtual灬zzZ

apollo动态刷新,应用在@value这种注入方式的属性没有问题,但是如果使用@ConfigurationProperties注解的bean,动态刷新就不好使了,会注入不到的。

@ConfigurationProperties如果需要在Apollo配置变化时自动更新注入的值,需要配合使用EnvironmentChangeEventRefreshScope

比如我们自定义的某个bean,也有spring cloud gateway 注入routeDefination 那样嵌死在源码里头,我们都可以使用官网给出的方式去解决。

https://www.apolloconfig.com/#/zh/usage/java-sdk-user-guide?id=_3223-configurationproperties%e4%bd%bf%e7%94%a8%e6%96%b9%e5%bc%8f

有两种方式:

https://gitee.com/apolloconfig/apollo-use-cases/blob/master/spring-cloud-zuul/src/main/java/com/ctrip/framework/apollo/use/cases/spring/cloud/zuul/ZuulPropertiesRefresher.java

@Component
public class RefresherApolloConfig implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @ApolloConfigChangeListener(interestedKeyPrefixes = "spring.cloud.gateway.")
    public void onChange(ConfigChangeEvent changeEvent) {
        refreshGatewayProperties(changeEvent);
    }

    private void refreshGatewayProperties(ConfigChangeEvent changeEvent) {
        System.out.println("Refreshing spring cloud gateway properties!");

        /**
         * rebind configuration beans
         */
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));

        System.out.println("spring cloud gateway properties refreshed!");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}


https://gitee.com/apolloconfig/apollo/blob/1.8.2/apollo-demo/src/main/java/com/ctrip/framework/apollo/demo/spring/springBootDemo/refresh/SpringBootApolloRefreshConfig.java

如果自定义的bean使用哪种都可以,@RefreshScope注解到@ConfigurationProperties修饰的bean,或者自己实现ApplicationContextAware 接口,如果是源码内嵌那种,就使用实现ApplicationContextAware 接口。

上一篇下一篇

猜你喜欢

热点阅读