RefreshScope注解类实例化基本流程
ScopedProxyFactoryBean的setBeanFactory
下面就开始创建这个CGLIB
动态代理对象,主要也就是scopedTargetSource
设置了工厂,然后添加了DelegatingIntroductionInterceptor
拦截器。
@Override
public void setBeanFactory(BeanFactory beanFactory) {
if (!(beanFactory instanceof ConfigurableBeanFactory)) {
throw new IllegalStateException("Not running in a ConfigurableBeanFactory: " + beanFactory);
}
ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) beanFactory;
//设置工厂,以便于后面获取代理对象
this.scopedTargetSource.setBeanFactory(beanFactory);
ProxyFactory pf = new ProxyFactory();
pf.copyFrom(this);
pf.setTargetSource(this.scopedTargetSource);
Assert.notNull(this.targetBeanName, "Property 'targetBeanName' is required");
Class<?> beanType = beanFactory.getType(this.targetBeanName);
if (beanType == null) {
throw new IllegalStateException("Cannot create scoped proxy for bean '" + this.targetBeanName +
"': Target type could not be determined at the time of proxy creation.");
}
if (!isProxyTargetClass() || beanType.isInterface() || Modifier.isPrivate(beanType.getModifiers())) {
pf.setInterfaces(ClassUtils.getAllInterfacesForClass(beanType, cbf.getBeanClassLoader()));
}
// 添加一个DelegatingIntroductionInterceptor拦截器
ScopedObject scopedObject = new DefaultScopedObject(cbf, this.scopedTargetSource.getTargetBeanName());
pf.addAdvice(new DelegatingIntroductionInterceptor(scopedObject));
pf.addInterface(AopInfrastructureBean.class);//标记接口
this.proxy = pf.getProxy(cbf.getBeanClassLoader());//创建cglib动态代理
}
LockedScopedProxyFactoryBean的setBeanFactory
继续回到这里,动态代理对象创建完之后就可以获取了:
然后将自己也加入增强器里,放在第一个位置上,优先执行。
增强后的:
也就是说这个代理对象有两个拦截器,一个是LockedScopedProxyFactoryBean
,一个是DelegatingIntroductionInterceptor
,调用方法的时候会先通过他们,但是后面你会发现LockedScopedProxyFactoryBean
拦截之后直接返回了,不会执行后面的拦截器了。
RefreshScope的eagerlyInitialize
上下文刷新完成的最后会进行ContextRefreshedEvent
事件的通知。
最后到eagerlyInitialize
方法中,这里会遍历所有的bean名字,找出bean
定义的scope=refresh
的且非懒加载的,然后进行一次获取,就是提前实例化啦。
private void eagerlyInitialize() {
for (String name : this.context.getBeanDefinitionNames()) {
BeanDefinition definition = this.registry.getBeanDefinition(name);
if (this.getName().equals(definition.getScope())//范围名字是refresh
&& !definition.isLazyInit()) {
Object bean = this.context.getBean(name);
if (bean != null) {
bean.getClass();
}
}
}
}
实例化的操作可跟一般的不一样,我们下次说。
好了,今天就到这里了,希望对学习理解有帮助,大神看见勿喷,仅为自己的学习理解,能力有限,请多包涵