代理对象的创建时机位于Bean的初始化之后,调用Bean的后置处理器AnnotationAwareAspectJAutoProxyCreator
的postProcessAfterInitialization
方法
postProcessAfterInitialization
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization
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;
}
按需生成代理对象,org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary
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.
/**
* @see AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean(java.lang.Class, java.lang.String, org.springframework.aop.TargetSource)
*/
// 获取与当前Bean匹配的切面
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;
}
解析@Aspect注解,生成Advisor
找被切面增强的Advisor
@Override
@Nullable
protected Object[] getAdvicesAndAdvisorsForBean(
Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
if (advisors.isEmpty()) {
return DO_NOT_PROXY;
}
return advisors.toArray();
}
AbstractAdvisorAutoProxyCreator#findEligibleAdvisors
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
/**
* @see AnnotationAwareAspectJAutoProxyCreator#findCandidateAdvisors()
*/
// 获取容器中所有的切面Advisor
// 这里返回的切面中的方法已经是有序的了,
//先按注解顺序(Around.class, Before.class, After.class, AfterReturning.class, AfterThrowing.class),再按方法名称
List<Advisor> candidateAdvisors = findCandidateAdvisors();
// 获取所有能够作用于当前Bean上的Advisor
List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
/**
* @see AspectJAwareAdvisorAutoProxyCreator#extendAdvisors(java.util.List)
*/
// 往集合第一个位置加入了一个DefaultPointcutAdvisor
extendAdvisors(eligibleAdvisors);
if (!eligibleAdvisors.isEmpty()) {
/**
* @see AspectJAwareAdvisorAutoProxyCreator#sortAdvisors(java.util.List)
*/
// 这里是对切面进行排序,例如有@Order注解或者实现了Ordered接口
eligibleAdvisors = sortAdvisors(eligibleAdvisors);
}
return eligibleAdvisors;
}
findCandidateAdvisors
protected List<Advisor> findCandidateAdvisors() {
// Add all the Spring advisors found according to superclass rules.
// 获取容器中所有的切面Advisor
List<Advisor> advisors = super.findCandidateAdvisors();
// Build Advisors for all AspectJ aspects in the bean factory.
if (this.aspectJAdvisorsBuilder != null) {
// 这里还需要解析@Aspect注解,生成Advisor
advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
}
return advisors;
}
findAdvisorsThatCanApply
org.springframework.aop.support.AopUtils#findAdvisorsThatCanApply
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
if (candidateAdvisors.isEmpty()) {
return candidateAdvisors;
}
List<Advisor> eligibleAdvisors = new ArrayList<>();
// InstantiationModelAwarePointcutAdvisorImpl
for (Advisor candidate : candidateAdvisors) {
if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
// IntroductionAdvisor类型为引入切面,具体类型为DeclareParentsAdvisor
eligibleAdvisors.add(candidate);
}
}
boolean hasIntroductions = !eligibleAdvisors.isEmpty();
for (Advisor candidate : candidateAdvisors) {
if (candidate instanceof IntroductionAdvisor) {
// already processed
continue;
}
// PointCut中的ClassFilter.match 匹配类
// PointCut中的MethodMatcher.match 匹配方法
if (canApply(candidate, clazz, hasIntroductions)) {
// @Aspect,类型为InstantiationModelAwarePointcutAdvisorImpl
eligibleAdvisors.add(candidate);
}
}
return eligibleAdvisors;
}
创建代理对象
在为业务逻辑组件创建代理对象的时候,使用的是cglib来创建动态代理的。当然了,如果业务逻辑类有实现接口,那么就使用jdk来创建动态代理。
protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
@Nullable Object[] specificInterceptors, TargetSource targetSource) {
if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
}
// 创建代理工厂
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.copyFrom(this);
if (!proxyFactory.isProxyTargetClass()) {
// 进来说明proxyTargetClass=false,指定JDK代理
if (shouldProxyTargetClass(beanClass, beanName)) {
// 进来这里说明BD中有个属性preserveTargetClass=true,可以BD中属性设置的优先级最高
proxyFactory.setProxyTargetClass(true);
}
else {
// 这里会判断bean有没有实现接口,没有就只能使用CGlib
evaluateProxyInterfaces(beanClass, proxyFactory);
}
}
Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
proxyFactory.addAdvisors(advisors); // 切面
proxyFactory.setTargetSource(targetSource); // 目标对象
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
}
// 使用JDK或者CGlib创建代理对象
return proxyFactory.getProxy(getProxyClassLoader());
}