在创建Bean的最后,会调用BeanPostProcessor方法;AOP本质上就是一个BeanPostProcessor。那么在创建Bean的最后,通过BeanPostProcessor方法生成代理类Bean,从而实现AOP功能。
1. AOP原理:applyBeanPostProcessorsAfterInitialization
在使用AOP时,要手动enable EnableAspectJAutoProxy, 由此也就引入了AnnotationAwareAspectJAutoProxyCreator 这个BeanPostProcessor, 于是在applyBeanPostProcessorsAfterInitialization 的函数中,会为bean创建AOP代理对象。
AnnotationAwareAspectJAutoProxyCreator
2. AOP对象生成(AbstractAutoProxyCreator)
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (!this.earlyProxyReferences.contains(cacheKey)) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
4. 生成代理类 wrapIfNecessary
protected Object wrapIfNecessary(){
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
//根据advice,生成代理bean
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
//不能生成代理类,返回初始bean
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
5. createProxy: Spring使用CGLib的方式生成代理类
protected Object createProxy(){
// 待补充
}