@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
// AOP的后置处理器,判断是否需要代理,如果需要则创建动态代理类
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
// 不存在,准备代理
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
重点是org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary
rotected 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.
// 这里返回的specificInterceptors 通知拦截器
// 就是前面解析的Advisors 通知器,这里根据方法匹配器进行匹配后过滤符合条件的
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
//要代理的就添加true
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;
}
这里做了两件事:
- 获取符合条件的通知器
- 创建代理对象
先看一下获取符合条件的通知器
prot