Apollo——@Value自动更新的实现

上次测试Apollo发现@Value注解获取的值会实时更新,挺好奇的,就研究了一下。

1、AutoUpdateConfigChangeListener监听器的设置 通过@EnableApolloConfig引入ApolloConfigRegistrar 调用了ApolloConfigRegistrarHelper的registerBeanDefinitions,进入该方法 PropertySourcesProcessor 实现了了 BeanFactoryPostProcessor,看其postProcessBeanFactory方法 initializePropertySources实现了讲配置放到Environment中,并保证了高优先级 initializeAutoUpdatePropertiesFeature实现了监听器的设置 2、@Value注解的处理 ApolloProcessor 实现了BeanPostProcessor,在postProcessBeforeInitialization中对字段和方法进行了处理。 在ApolloProcessor 子类SpringValueProcessor中processField、和 processMethod 对注解@Value进行了处理 在ApolloProcessor 子类ApolloAnnotationProcessor中processMethod对注解@ApolloConfigChangeListener进行了处理,@ApolloConfigChangeListener的处理逻辑在这里实现(不是本篇的重点)

看一下SpringValueProcessor中processField方法 (1)判断字段是否被@Value标记,如果没有则返回,有则继续往下 (2)解析@Value注解里面设置的value (3)构造SpringValue对象 new SpringValue(key, value.value(), bean, beanName, field, false) (4)将构造的springValue存到SpringValueRegistry的Map<BeanFactory, Multimap<String, SpringValue>>中

3、AutoUpdateConfigChangeListener修改值 当修改配置发布事件后,AutoUpdateConfigChangeListener就被触发onChange(ConfigChangeEvent changeEvent)事件 (1)通过event拿到所有变更的keys (2)遍历keys,通过springValueRegistry.get(beanFactory, key) 拿到SpringValue集合对象 (3)判断配置是否真的发生了变化 shouldTriggerAutoUpdate(changeEvent, key) (4)遍历SpringValue集合,逐一通过反射改变字段的值

参考

经验分享 程序员 微信小程序 职场和发展