Spring5.2.x源码阅读之大致脉络梳理
Spring5.2.x源码阅读之容器和对象的创建流程
一、提到Spring就得提到Spring中的IOC和AOP,同时也能想起Spring容器。从对象的创建、使用到销毁均是在Spring容器中进行的。
二、Spring中对象的创建方式有两种
1、通过xml方式创建
2、通过注解@Bean
三、容器和Bean的创建流程:
1、先创建容器,也可以讲是创建BeanFactory,因为BeanFactory中有个方法是getBean。
2、加载配置文件如xml文件等,配置文件加载完成后就封装成了BeanDefinition。配置文件还有yml文件和properties文件,以及注解等,他们都可以被加载封装成BeanDefinition。往后还有可能有其他的,为了便于扩展。所以引入了BeanDefinitionReader这个接口,通过其不同的子类实现即可。
3、调用BeanFactoryPostProcessor。做一些BeanFactory的增强处理的工作。
准备工作:
准备BeanPostProcess、准备监听器、事件、广播器。
4、实例化,在堆中开辟空间,属性赋初始值。
5、初始化,填充属性,调用初始化方法,完成额外的扩展功能。
6、完成的Bean对象
什么是PostProcessor?
四、Spring中的对象按照使用者可以分为两类
1、自定义对象,如何在自定义对象中获取到容器对象?可以实现BeanFactoryAware、ApplicationContextAware接口。两接口定义的方法如下。
public interface ApplicationContextAware extends Aware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
public interface BeanFactoryAware extends Aware {
void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}
2、容器对象
五、BeanPostProcessor对Bean的增强处理这一块实际上就是我们心心念念的AOP
进入BeanPostProcessor,找到其抽象子类AbstractAutoProxyCreator
进入postProcessAfterInitialization方法,再进入wrapIfNecessary
/**
* Create a proxy with the configured interceptors if the bean is
* identified as one to proxy by the subclass.
* @see #getAdvicesAndAdvisorsForBean
*/
@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
再进入wrapIfNecessary方法中的createProxy方法
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
}
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
// Create proxy if we have advice.
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
进入proxyFactory的getProxy方法。
protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
......
return proxyFactory.getProxy(getProxyClassLoader());
}
public Object getProxy(@Nullable ClassLoader classLoader) {
return createAopProxy().getProxy(classLoader);
}
再进入AopProxy接口中的getProxy方法。查看其子类实现发现正是我们需要找的CglibAopProxy和JdkDynamicAopProxy。