源码分析
宏观流程解析
1.spring对@RefreshScopre注解的bean做的事情
1.当调用被@RefreshScope注解的bean的属性的get方法时 则先从本地缓存里面获取
2.当本地缓存中 不存在当前bean时 则重新创建 此时 会获取 spring中最新环境配置
3.如果本地缓存中 存在当前 bean则 直接返回对应属性值
2.nacos对@RefreshScopre注解的bean做的事情
1.当配置更改时 nacos服务端会发步一个配置已被更新事件
2.此时 naocs客户端 会接受到这个事件 接受到以后 会再在spring中发布环境配置刷新事件
3.然后 对应的监听器 收到以后 则刷新spring环境配置 以及 清空本地缓存
源码解析
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Scope("refresh")
@Documented
public @interface RefreshScope {
/**
* @see Scope#proxyMode()
* @return proxy mode
*/
ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;
}
org.springframework.context.annotation.ClassPathBeanDefinitionScanner#doScan
org.springframework.context.annotation.AnnotationConfigUtils#applyScopedProxyMode
-->org.springframework.context.annotation.ScopedProxyCreator#createScopedProxy
-->org.springframework.aop.scope.ScopedProxyUtils#createScopedProxy
org.springframework.cloud.context.scope.GenericScope#postProcessBeanDefinitionRegistry
org.springframework.cloud.context.scope.GenericScope.LockedScopedProxyFactoryBean#setBeanFactory
org.springframework.aop.scope.ScopedProxyFactoryBean#setBeanFactory
创建代理
------由上可知,被@RefreshScope注解的bean被包装为一个FactoryBean(org.springframework.cloud.context.scope.GenericScope.LockedScopedProxyFactoryBean),由此调用时就会调用getObject()方法,这样就会得到一个代理对象,执行时会获取到目标对象 SimpleBeanTargetSource.getTarget(),以"scopedTarget."开头的bean,接下来看一下该bean的创建时机
创建target
org.springframework.cloud.context.scope.refresh.RefreshScope#onApplicationEvent
org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
org.springframework.cloud.context.scope.GenericScope#get
以上即@RefreshScope的相关对象的创建
由上可知,目标类都会存于scope的cache里
-----------------------------------------------------------------------------------
NacosContextRefresher(nacos配置刷新)
public class NacosContextRefresher
implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware
{
public void onApplicationEvent(ApplicationReadyEvent event) {
// many Spring context
if (this.ready.compareAndSet(false, true)) {
this.registerNacosListenersForApplications();
}
}
}
com.alibaba.cloud.nacos.refresh.NacosContextRefresher#registerNacosListenersForApplications
--->com.alibaba.cloud.nacos.refresh.NacosContextRefresher#registerNacosListener
注册监听器,监听nacos配置变化,并发布RefreshEvent
org.springframework.cloud.endpoint.event.RefreshEventListener#onApplicationEvent
org.springframework.cloud.context.refresh.ContextRefresher#refresh
1.刷新了环境,2清空cache
首先刷新环境
如下,有个前后对比,关键就在addConfigFilesToEnvironment()
首先copyEnvironment,虽说是copy,这里只保留了一些最基本的配置,如下
第二步,创建Spring容器 capture = builder.run();
这里还是走之前的逻辑,具体可参考
只是这次创建的两个Spring容器都为AnnotationConfigApplicationContext,并且用完就关了
我们看一下方法执行之后的environment
之后的逻辑就是对比两个环境进行替换了,这就是刷新环境的大致流程
然后清空cache