继续上一篇
追踪了一下代码,找到了springAOP启动时注册的代理类
类AnnotationAwareAspectJAutoProxyCreator 是处理切面xml配置spirngaop或者注解创建代理类的容器。
其父类AbstractAutoProxyCreator中根据配置的通知类型执行
postProcessBeforeInstantiation postProcessAfterInitialization 方法
然后调用wrapIfNecessary方法将需要切面的方法存入map advisedBeans
/**
* Wrap the given bean if necessary, i.e. if it is eligible for being proxied.
* @param bean the raw bean instance
* @param beanName the name of the bean
* @param cacheKey the cache key for metadata access
* @return a proxy wrapping the bean, or the raw bean instance as-is
*/
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (beanName != null && this.targetSourcedBeans.containsKey(beanName)) {
returnbean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
returnbean;
}
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
returnbean;
}
// 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());
returnproxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
returnbean;
}
其中
Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
通过代理的方式将所要切面处理的对象代理出来
代理的方式分为JDK原声的代理,以及cglib
JDK:所代理的对象实现了接口
cglib:所代理的对象没有接口实现
至此,springaop代理对象已成功,
当调用到切点所在的方法时,反射代理对象的方法,
再根据通知的类型来执行代理对象的前后操作
调用JdkDynamicAopProxy类中的
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
。。。
方法