代理对象的创建
getObject--》
void org.springframework.aop.framework.ProxyFactoryBean.initializeAdvisorChain() throws AopConfigException, BeansException
初始化拦截器链路--》
addAdvisorOnChainCreation(advice, name);找到advisor并添加--》
this.advisors.add(pos, advisor);设置advisors集合。--》
然后创建代理对象,可以用JDK动态代理或者CGLIB字节码加强。
ProxyFactoryBean继承了AdvisedSupport,在创建AopProxy(例如org.springframework.aop.framework.JdkDynamicAopProxy)实例的时候会把自己传递过去,也就是AopProxy持有一个AdvisedSupport,也就只有了advisors——》简单来说,aop代理对象知道自己上有哪些拦截器(通知器),在invoke的时候来解析。--》
invoke 以JDK动态代理为例
Object org.springframework.aop.framework.JdkDynamicAopProxy.invoke(Object proxy, Method method, Object[] args)
//目标对象
target = targetSource.getTarget();
// Get the interception chain for this method.
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
获取拦截器链路
然后构造一个MethodInvocation——invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);递归调用
拦截器链路的获取:List<Object> org.springframework.aop.framework.AdvisedSupport.getInterceptorsAndDynamicInterceptionAdvice(Method method, Class targetClass)回归到了AdvisedSupport
cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
this, method, targetClass);--》
List<Object> org.springframework.aop.framework.DefaultAdvisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class targetClass)
boolean hasIntroductions = hasMatchingIntroductions(config, targetClass);//检查是否有IntroductionAdvisor配置
for (Advisor advisor : config.getAdvisors()) {开始处理config其实就是我们前面提到的那个AdvisedSupport,它代表了配置,持有所有通知器
。。。
MethodInterceptor[] interceptors = registry.getInterceptors(advisor);//Advisor中提取MethodInterceptor,这个很重要,不管是通知还是拦截器统统转换为MethodInterceptor
--》
MethodInterceptor[] org.springframework.aop.framework.adapter.DefaultAdvisorAdapterRegistry.getInterceptors(Advisor advisor) throws UnknownAdviceTypeException
这是一个适配器,可以处理本来就是MethodInterceptor的,也可以处理各种Advice(如MethodBeforeAdvice):
//如果是MethodInterceptor
if (advice instanceof MethodInterceptor) {
interceptors.add((MethodInterceptor) advice);
}
//如果是其他通知器
for (AdvisorAdapter adapter : this.adapters) {//各种适配器将Advice转换为MethodInterceptor
if (adapter.supportsAdvice(advice)) {
interceptors.add(adapter.getInterceptor(advisor));
}
}
adapter有三种:MethodBeforeAdviceAdapter、AfterReturningAdviceAdapter、ThrowsAdviceAdapter他们都实现了这样的接口adapter.getInterceptor(advisor),如
class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {
public boolean supportsAdvice(Advice advice) {
return (advice instanceof MethodBeforeAdvice);
}
//将MethodBeforeAdvice提取出来转换成MethodBeforeAdviceInterceptor(实现了MethodInterceptor接口),那么在构造MethodInvocation一次调用各拦截器invoke方法的时候,就变成了前置、后置、环绕处理。
public MethodInterceptor getInterceptor(Advisor advisor) {
MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
return new MethodBeforeAdviceInterceptor(advice);
}
}