@Overridepublic Object invoke(Object proxy, Methodmethod, Object[] args) throwsThrowable{
MethodInvocation invocation;
Object oldProxy = null;
boolean setProxyContext = false;
TargetSource targetSource = this.advised.targetSource;
Class> targetClass = null;
Object target = null;
try {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// If the target does not implement the equals(Object) method itself.
return equals(args[0]);
}if(!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// If the target does not implement the hashCode() method itself.
return hashCode();
}if(!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
// Service invocations on ProxyConfig with the proxy config...
// 根据代理对象的配置来调用服务
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}ObjectretVal;if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}// May be null. Get as late as possible to minimize the time we "own" the target,// in case it comes from a pool.// 得到目标对象的地方
target = targetSource.getTarget();
if (target != null) {
targetClass = target.getClass();
}// Get the interception chain for this method.// 这里是定义好的拦截器链
List
可以看到在执行拦截器链是递归前进的:
ReflectiveMethodInvocation的proceed
@Overridepublic Object proceed() throws Throwable {
// We start with an index of -1 and increment early.// 从索引为-1的拦截器开始调用,并按序递增// 如果拦截器链中的拦截器迭代调用完毕,这里开始调用target函数,通过反射// AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}
// 这里沿着定义好的 interceptorOrInterceptionAdvice链进行处理
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
// Evaluate dynamic method matcher here: static part will already have// been evaluated and found to match.// 这里对拦截器链进行匹配,如果和定义的PointCut匹配,这个Advice会得到执行
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
return dm.interceptor.invoke(this);
}
else {
// Dynamic matching failed.// Skip this interceptor and invoke the next in the chain.// 如果不匹配,那么proceed递归调用,知道所有的拦截器都被运行过为止return proceed();
}
}
else {
// It's an interceptor, so we just invoke it: The pointcut will have// been evaluated statically before this object was constructed.// 如果是一个interceptor,直接调用这个interceptor对应的方法return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
Cglib2AopProxy的拦截
DynamicAdvisedInteceptor的intercept:
privatestaticclassDynamicAdvisedInterceptorimplementsMethodInterceptor, Serializable {privatefinal AdvisedSupport advised;
publicDynamicAdvisedInterceptor(AdvisedSupport advised) {
this.advised = advised;
}
@Overridepublic Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;
Class> targetClass = null;
Object target = null;
try {
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// May be null. Get as late as possible to minimize the time we// "own" the target, in case it comes from a pool...
target = getTarget();
if (target != null) {
targetClass = target.getClass();
}
// 从advised中取得配置好的通知
List
privatesynchronizedvoidinitializeAdvisorChain() throws AopConfigException, BeansException {
if (this.advisorChainInitialized) {
return;
}
if (!ObjectUtils.isEmpty(this.interceptorNames)) {
if (this.beanFactory == null) {
thrownew IllegalStateException("No BeanFactory available anymore (probably due to serialization) " +
"- cannot resolve interceptor names " + Arrays.asList(this.interceptorNames));
}
// Globals can't be last unless we specified a targetSource using the property...if (this.interceptorNames[this.interceptorNames.length - 1].endsWith(GLOBAL_SUFFIX) &&
this.targetName == null && this.targetSource == EMPTY_TARGET_SOURCE) {
thrownew AopConfigException("Target required after globals");
}
// Materialize interceptor chain from bean names.for (String name : this.interceptorNames) {
if (logger.isTraceEnabled()) {
logger.trace("Configuring advisor or advice '" + name + "'");
}
if (name.endsWith(GLOBAL_SUFFIX)) {
if (!(this.beanFactory instanceof ListableBeanFactory)) {
thrownew AopConfigException(
"Can only use global advisors or interceptors with a ListableBeanFactory");
}
addGlobalAdvisor((ListableBeanFactory) this.beanFactory,
name.substring(0, name.length() - GLOBAL_SUFFIX.length()));
}
else {
// If we get here, we need to add a named interceptor.// We must check if it's a singleton or prototype.
Object advice;
// 判断Bean类型是singleTon还是protoTypeif (this.singleton || this.beanFactory.isSingleton(name)) {
// Add the real Advisor/Advice to the chain.// 这里取得advisor的地方,是通过BeanFactory获得的// 把interceptNames这个List中的interceptor名字交给BeanFactory,然后通过BeanFactory的getBean获取
advice = this.beanFactory.getBean(name);
}
else {
// It's a prototype Advice or Advisor: replace with a prototype.// Avoid unnecessary creation of prototype bean just for advisor chain initialization.// 如果bean类型是Prototype
advice = new PrototypePlaceholderAdvisor(name);
}
addAdvisorOnChainCreation(advice, name);
}
}
}
this.advisorChainInitialized = true;
}
publicclassProxyFactoryextendsProxyCreatorSupport {/**
* Create a new ProxyFactory.
*/publicProxyFactory() {
}
/**
* Create a new ProxyFactory.
*
Will proxy all interfaces that the given target implements.
* @param target the target object to be proxied
*/
publicProxyFactory(Object target) {
setTarget(target);
setInterfaces(ClassUtils.getAllInterfaces(target));
}
/**
* Create a new ProxyFactory.
*
No target, only interfaces. Must add interceptors.
* @param proxyInterfaces the interfaces that the proxy should implement
*/
publicProxyFactory(Class>... proxyInterfaces) {
setInterfaces(proxyInterfaces);
}
/**
* Create a new ProxyFactory for the given interface and interceptor.
*
Convenience method for creating a proxy for a single interceptor,
* assuming that the interceptor handles all calls itself rather than
* delegating to a target, like in the case of remoting proxies.
* @param proxyInterface the interface that the proxy should implement
* @param interceptor the interceptor that the proxy should invoke
*/
publicProxyFactory(Class> proxyInterface, Interceptor interceptor) {
addInterface(proxyInterface);
addAdvice(interceptor);
}
/**
* Create a ProxyFactory for the specified {@code TargetSource},
* making the proxy implement the specified interface.
* @param proxyInterface the interface that the proxy should implement
* @param targetSource the TargetSource that the proxy should invoke
*/publicProxyFactory(Class> proxyInterface, TargetSource targetSource) {
addInterface(proxyInterface);
setTargetSource(targetSource);
}
/**
* Create a new proxy according to the settings in this factory.
*
Can be called repeatedly. Effect will vary if we've added
* or removed interfaces. Can add and remove interceptors.
*
Uses a default class loader: Usually, the thread context class loader
* (if necessary for proxy creation).
* @return the proxy object
*/
public Object getProxy() {
return createAopProxy().getProxy();
}
/**
* Create a new proxy according to the settings in this factory.
*
Can be called repeatedly. Effect will vary if we've added
* or removed interfaces. Can add and remove interceptors.
*
Uses the given class loader (if necessary for proxy creation).
* @param classLoader the class loader to create the proxy with
* (or {@code null} for the low-level proxy facility's default)
* @return the proxy object
*/
public Object getProxy(ClassLoader classLoader) {
return createAopProxy().getProxy(classLoader);
}
/**
* Create a new proxy for the given interface and interceptor.
*
Convenience method for creating a proxy for a single interceptor,
* assuming that the interceptor handles all calls itself rather than
* delegating to a target, like in the case of remoting proxies.
* @param proxyInterface the interface that the proxy should implement
* @param interceptor the interceptor that the proxy should invoke
* @return the proxy object
* @see #ProxyFactory(Class, org.aopalliance.intercept.Interceptor)
*/
@SuppressWarnings("unchecked")
publicstatic T getProxy(Class proxyInterface, Interceptor interceptor) {
return (T) new ProxyFactory(proxyInterface, interceptor).getProxy();
}
/**
* Create a proxy for the specified {@code TargetSource},
* implementing the specified interface.
* @param proxyInterface the interface that the proxy should implement
* @param targetSource the TargetSource that the proxy should invoke
* @return the proxy object
* @see #ProxyFactory(Class, org.springframework.aop.TargetSource)
*/@SuppressWarnings("unchecked")
publicstatic T getProxy(Class proxyInterface, TargetSource targetSource) {
return (T) new ProxyFactory(proxyInterface, targetSource).getProxy();
}
/**
* Create a proxy for the specified {@code TargetSource} that extends
* the target class of the {@code TargetSource}.
* @param targetSource the TargetSource that the proxy should invoke
* @return the proxy object
*/publicstatic Object getProxy(TargetSource targetSource) {
if (targetSource.getTargetClass() == null) {
thrownew IllegalArgumentException("Cannot create class proxy for TargetSource with null target class");
}
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTargetSource(targetSource);
proxyFactory.setProxyTargetClass(true);
return proxyFactory.getProxy();
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml&q