您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“@RereshScope刷新的原理是什么”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“@RereshScope刷新的原理是什么”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。
在配合配置中心修改配置讓應(yīng)用自動(dòng)刷新配置時(shí),我們要在需要感知配置變化的bean上面加上@RereshScope
。如果我們不加上這注解,那么有可能無法完成配置自動(dòng)刷新。
可以看到@RereshScope
是@Scope("refresh")
(bean的作用域)的派生注解并指定了作用域?yàn)?code>refresh并在默認(rèn)情況下proxyMode= ScopedProxyMode.TARGET_CLASS
即使用CGLIB生成代理對(duì)象。
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Scope("refresh") @Documented public @interface RefreshScope { ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS; }
ScopedProxyMode
表示作用域的代理模式,共有以下四個(gè)值:
DEFAULT
:默認(rèn)no
NO
:不使用代理
INTERFACES
:使用JDK動(dòng)態(tài)代理
TARGET_CLASS
:使用CGLIB動(dòng)態(tài)代理
public enum ScopedProxyMode { /** * Default typically equals {@link #NO}, unless a different default * has been configured at the component-scan instruction level. */ DEFAULT, /** * Do not create a scoped proxy. */ NO, /** * Create a JDK dynamic proxy implementing <i>all</i> interfaces exposed by * the class of the target object. */ INTERFACES, /** * Create a class-based proxy (uses CGLIB). */ TARGET_CLASS; }
在上文刷新時(shí)會(huì)執(zhí)行BeanFacotryPostProcessor
對(duì)beanDefinition
修改和增加,其中配置類解析、類掃描的工作就是在其中執(zhí)行,而對(duì)于一個(gè)ScopedProxyMode.NO
它會(huì)解析成一個(gè)ScopedProxyFactoryBean
//ConfigurationClassBeanDefinitionReader配置類解析代碼片段 definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); //如果需要生產(chǎn)代理則創(chuàng)建一個(gè)ScopedProxy的BeanDefinition static BeanDefinitionHolder applyScopedProxyMode( ScopeMetadata metadata, BeanDefinitionHolder definition, BeanDefinitionRegistry registry) { ScopedProxyMode scopedProxyMode = metadata.getScopedProxyMode(); if (scopedProxyMode.equals(ScopedProxyMode.NO)) { return definition; } boolean proxyTargetClass = scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS); return ScopedProxyCreator.createScopedProxy(definition, registry, proxyTargetClass); } //createScopedProxy 代碼片段 可以看到BeanDefinition是ScopedProxyFactoryBean RootBeanDefinition proxyDefinition = new RootBeanDefinition(ScopedProxyFactoryBean.class);
FactoryBean
在注入時(shí)返回的是getObject()
所返回的對(duì)象,在這里就是返回的就是proxy
。ScopedProxyFactoryBean
實(shí)現(xiàn)了BeanFactoryAware
那么在這個(gè)bean初始化中會(huì)調(diào)用setBeanFactory()
方法,而在這個(gè)方法中,為它創(chuàng)建一個(gè)CGLIB
代理對(duì)象作為getObject()
的返回值,并使用ScopedObject
來代替被代理對(duì)象。而在ScopedObject
默認(rèn)實(shí)現(xiàn)中每次都是從BeanFactory
中獲?。ㄖ攸c(diǎn))。
@Override public Object getObject() { if (this.proxy == null) { throw new FactoryBeanNotInitializedException(); } //返回代理對(duì)象 return this.proxy; } @Override public void setBeanFactory(BeanFactory beanFactory) { //...省略其他代碼 // Add an introduction that implements only the methods on ScopedObject. //增加一個(gè)攔截使用ScopedObject來被代理對(duì)象調(diào)用方法 ScopedObject scopedObject = new DefaultScopedObject(cbf, this.scopedTargetSource.getTargetBeanName()); //委托ScopedObject去執(zhí)行 pf.addAdvice(new DelegatingIntroductionInterceptor(scopedObject)); // Add the AopInfrastructureBean marker to indicate that the scoped proxy // itself is not subject to auto-proxying! Only its target bean is. AOP時(shí)復(fù)用這個(gè)代理對(duì)象 pf.addInterface(AopInfrastructureBean.class); //創(chuàng)建代理對(duì)象 this.proxy = pf.getProxy(cbf.getBeanClassLoader()); }
作用域?qū)ο蟮?code>AOP引入的接口??梢詫?code>ScopedProxyFactoryBean創(chuàng)建的對(duì)象強(qiáng)制轉(zhuǎn)換到此接口,從而可以控制訪問原始目標(biāo)對(duì)象并通過編程刪除目標(biāo)對(duì)象。在默認(rèn)實(shí)現(xiàn)中是每次方法攔截都從容器中獲取被代理的目標(biāo)對(duì)象。
public interface ScopedObject extends RawTargetAccess { //返回當(dāng)前代理對(duì)象后面的目標(biāo)對(duì)象 Object getTargetObject(); void removeFromScope(); } public class DefaultScopedObject implements ScopedObject, Serializable { //...省略字段信息和構(gòu)造器 @Override public Object getTargetObject() { //從容器中獲取 return this.beanFactory.getBean(this.targetBeanName); } @Override public void removeFromScope() { this.beanFactory.destroyScopedBean(this.targetBeanName); } }
在BeanFactory
獲取bean時(shí)(doGetBean
),如果**不是單例或者原型bean
**將交給對(duì)應(yīng)的Socpe
去bean
,而創(chuàng)建bean
方式和單例bean是一樣的。其他作用域像request
、session
等等都是屬于這一塊的擴(kuò)展:SPI+策略模式
//AbstractBeanFactory doGetBean()代碼片段 String scopeName = mbd.getScope(); //獲取對(duì)應(yīng)的scope final Scope scope = this.scopes.get(scopeName); //參數(shù)檢查省略。。。 try { //使用的對(duì)應(yīng)的Socpe去獲取bean 獲取不到則使用后面的`ObjectFactory` Object scopedInstance = scope.get(beanName, () -> { //ObjectFactory lambda表達(dá)式 怎么創(chuàng)建bean beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
RefreshScope
繼承GenericScope
每次獲取bean是從自己的緩存(ConcurrentHashMap
)中獲取。 如果緩存中bean被銷毀了則用objectFactory
創(chuàng)建一個(gè)。
//GenericScope 中獲取get實(shí)現(xiàn) public Object get(String name, ObjectFactory<?> objectFactory) { //從緩存中獲取 緩存的實(shí)現(xiàn)就是ConcurrentHashMap BeanLifecycleWrapper value = this.cache.put(name, new BeanLifecycleWrapper(name, objectFactory)); this.locks.putIfAbsent(name, new ReentrantReadWriteLock()); try { return value.getBean(); } catch (RuntimeException var5) { this.errors.put(name, var5); throw var5; } }
private static class BeanLifecycleWrapper { //當(dāng)前bean對(duì)象 private Object bean; //銷毀回調(diào) private Runnable callback; //bean名稱 private final String name; //bean工廠 private final ObjectFactory<?> objectFactory; //獲取 public Object getBean() { if (this.bean == null) { synchronized(this.name) { if (this.bean == null) { this.bean = this.objectFactory.getObject(); } } } return this.bean; } //銷毀 public void destroy() { if (this.callback != null) { synchronized(this.name) { Runnable callback = this.callback; if (callback != null) { callback.run(); } this.callback = null; //只為null this.bean = null; } } } }
當(dāng)配置中心刷新配置之后,有兩種方式可以動(dòng)態(tài)刷新Bean的配置變量值,(SpringCloud-Bus
還是Nacos
差不多都是這么實(shí)現(xiàn)的):
向上下文發(fā)布一個(gè)RefreshEvent
事件
Http
訪問/refresh
這個(gè)EndPoint
不管是什么方式,最終都會(huì)調(diào)用ContextRefresher
這個(gè)類的refresh
方法
public synchronized Set<String> refresh() { //刷新環(huán)境 Set<String> keys = this.refreshEnvironment(); //刷新bean 其實(shí)就是銷毀refreshScope中緩存的bean this.scope.refreshAll(); return keys; } //RefreshScope刷新 public void refreshAll() { super.destroy(); this.context.publishEvent(new RefreshScopeRefreshedEvent()); }
讀到這里,這篇“@RereshScope刷新的原理是什么”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。