您的位置:首页 > 编程语言 > Java开发

Spring AOP 源码

2016-07-29 10:19 99 查看

Advice通知:

public interface Advice {

}
public interface BeforeAdvice extends Advice {

}
public interface MethodBeforeAdvice extends BeforeAdvice {

// 实现回调函数
void before(Method method, Object[] args, Object target) throws Throwable;

}


PointCut 切点:

public interface Pointcut {

ClassFilter getClassFilter();

MethodMatcher getMethodMatcher();

Pointcut TRUE = TruePointcut.INSTANCE;

}


实现

@SuppressWarnings("serial")
public class JdkRegexpMethodPointcut extends AbstractRegexpMethodPointcut {

private Pattern[] compiledPatterns = new Pattern[0];

private Pattern[] compiledExclusionPatterns = new Pattern[0];

@Override
protected void initPatternRepresentation(String[] patterns) throws PatternSyntaxException {
this.compiledPatterns = compilePatterns(patterns);
}

@Override
protected void initExcludedPatternRepresentation(String[] excludedPatterns) throws PatternSyntaxException {
this.compiledExclusionPatterns = compilePatterns(excludedPatterns);
}

// 匹配方法名
@Override
protected boolean matches(String pattern, int patternIndex) {
Matcher matcher = this.compiledPatterns[patternIndex].matcher(pattern);
return matcher.matches();
}

@Override
protected boolean matchesExclusion(String candidate, int patternIndex) {
Matcher matcher = this.compiledExclusionPatterns[patternIndex].matcher(candidate);
return matcher.matches();
}

private Pattern[] compilePatterns(String[] source) throws PatternSyntaxException {
Pattern[] destination = new Pattern[source.length];
for (int i = 0; i < source.length; i++) {
destination[i] = Pattern.compile(source[i]);
}
return destination;
}

}


Adviser 通知器:

@SuppressWarnings("serial")
public class DefaultPointcutAdvisor extends AbstractGenericPointcutAdvisor implements Serializable {

// 切点
private Pointcut pointcut = Pointcut.TRUE;

public DefaultPointcutAdvisor() {
}

// 通知
public DefaultPointcutAdvisor(Advice advice) {
this(Pointcut.TRUE, advice);
}

public DefaultPointcutAdvisor(Pointcut pointcut, Advice advice) {
this.pointcut = pointcut;
setAdvice(advice);
}

public void setPointcut(Pointcut pointcut) {
this.pointcut = (pointcut != null ? pointcut : Pointcut.TRUE);
}

@Override
public Pointcut getPointcut() {
return this.pointcut;
}

@Override
public String toString() {
return getClass().getName() + ": pointcut [" + getPointcut() + "]; advice [" + getAdvice() + "]";
}

}

class TruePointcut implements Pointcut, Serializable {

// 单例模式
public static final TruePointcut INSTANCE = new TruePointcut();

...
}


动态代理:

aop代理工厂:

public interface AopProxyFactory {

AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException;

}


默认代理工厂实现类:

public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {

@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
// 如果目标类型是接口,则使用JDK动态代理,因为cglib是采用继承的方式实现动态代理的
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}

private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
Class<?>[] ifcs = config.getProxiedInterfaces();
return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0])));
}

}


动态代理invoke方法实现:

final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {

...
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MethodInvocation invocation;
Object oldProxy = null;
boolean setProxyContext = false;

TargetSource targetSource = this.advised.targetSource;
Class<?> targetClass = null;
Object target = null;

try {
...

Object retVal;

if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}

// 得到目标对象
target = targetSource.getTarget();
if (target != null) {
targetClass = target.getClass();
}

// 得到拦截器链
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

if (chain.isEmpty()) {
// 如果没有设定拦截器,直接执行
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
// 如果有拦截器,则先进行拦截器操作再进行对应方法的执行
// 注意是拦截器列表
invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
// Proceed to the joinpoint through the interceptor chain.
retVal = invocation.proceed();
}

// Massage return value if necessary.
Class<?> returnType = method.getReturnType();
if (retVal != null && retVal == target && returnType.isInstance(proxy) &&
!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
// Special case: it returned "this" and the return type of the method
// is type-compatible. Note that we can't help if the target sets
// a reference to itself in another returned object.
retVal = proxy;
}
else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
throw new AopInvocationException(
"Null return value from advice does not match primitive return type for: " + method);
}
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
// Must have come from TargetSource.
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
AopContext.setCurrentProxy(oldProxy);
}
}
}
...

}


ReflectiveMethodInvocation :

public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable {

...

@Override
public Object proceed() throws Throwable {
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}

Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
// 进行拦截器操作成功,执行拦截器
return dm.interceptor.invoke(this);
}
else {
// 拦截失败,进行下一个拦截器的匹配进行,直至所有拦截器都被运行过
return proceed();
}
}
else {
// 如果是拦截器,直接获取拦截器直接执行
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}

...

}


获取拦截器链:

List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, Class<?> targetClass) {
// 利用缓存储存
MethodCacheKey cacheKey = new MethodCacheKey(method);
List<Object> cached = this.methodCache.get(cacheKey);
if (cached == null) {
// 首次生成
cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
this, method, targetClass);
// 加入缓存
this.methodCache.put(cacheKey, cached);
}
return cached;
}


DefaultAdvisorChainFactory 生成拦截器链:

public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class<?> targetClass) {
ArrayList interceptorList = new ArrayList(config.getAdvisors().length);
Class actualClass = targetClass != null?targetClass:method.getDeclaringClass();
boolean hasIntroductions = hasMatchingIntroductions(config, actualClass);
// 拦截器通过AdvisorAdapterRegistry进行注册
AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
Advisor[] var8 = config.getAdvisors();
int var9 = var8.length;

for(int var10 = 0; var10 < var9; ++var10) {
Advisor advisor = var8[var10];
MethodInterceptor[] interceptors1;
if(advisor instanceof PointcutAdvisor) {
PointcutAdvisor var20 = (PointcutAdvisor)advisor;
if(config.isPreFiltered() || var20.getPointcut().getClassFilter().matches(actualClass)) {
interceptors1 = registry.getInterceptors(advisor);
MethodMatcher mm = var20.getPointcut().getMethodMatcher();
if(MethodMatchers.matches(mm, method, actualClass, hasIntroductions)) {
if(mm.isRuntime()) {
MethodInterceptor[] var15 = interceptors1;
int var16 = interceptors1.length;

for(int var17 = 0; var17 < var16; ++var17) {
MethodInterceptor interceptor = var15[var17];
interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
}
} else {
interceptorList.addAll(Arrays.asList(interceptors1));
}
}
}
} else if(advisor instanceof IntroductionAdvisor) {
IntroductionAdvisor var19 = (IntroductionAdvisor)advisor;
if(config.isPreFiltered() || var19.getClassFilter().matches(actualClass)) {
interceptors1 = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors1));
}
} else {
MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}

return interceptorList;
}


Advisor的获取和初始化:

private synchronized void initializeAdvisorChain() throws AopConfigException, BeansException {
if(!this.advisorChainInitialized) {
if(!ObjectUtils.isEmpty(this.interceptorNames)) {
if(this.beanFactory == null) {
throw new IllegalStateException("No BeanFactory available anymore (probably due to serialization) - cannot resolve interceptor names " + Arrays.asList(this.interceptorNames));
}

if(this.interceptorNames[this.interceptorNames.length - 1].endsWith("*") && this.targetName == null && this.targetSource == EMPTY_TARGET_SOURCE) {
throw new AopConfigException("Target required after globals");
}

String[] var1 = this.interceptorNames;
int var2 = var1.length;

for(int var3 = 0; var3 < var2; ++var3) {
String name = var1[var3];
if(this.logger.isTraceEnabled()) {
this.logger.trace("Configuring advisor or advice \'" + name + "\'");
}

if(name.endsWith("*")) {
if(!(this.beanFactory instanceof ListableBeanFactory)) {
throw new AopConfigException("Can only use global advisors or interceptors with a ListableBeanFactory");
}

this.addGlobalAdvisor((ListableBeanFactory)this.beanFactory, name.substring(0, name.length() - "*".length()));
} else {
Object advice;
// 判断是否单件还是ProtoType类型
if(!this.singleton && !this.beanFactory.isSingleton(name)) {
// 获取bean,单件
advice = new ProxyFactoryBean.PrototypePlaceholderAdvisor(name);
} else {
// 生成bean,protoType
advice = this.beanFactory.getBean(name);
}

this.addAdvisorOnChainCreation(advice, name);
}
}
}

this.advisorChainInitialized = true;
}
}


Advice 通知的实现:

public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class<?> targetClass) {
ArrayList interceptorList = new ArrayList(config.getAdvisors().length);
Class actualClass = targetClass != null?targetClass:method.getDeclaringClass();
boolean hasIntroductions = hasMatchingIntroductions(config, actualClass);
// 得到注册器 DefaultAdvisorAdapterRegistry 注册单件
// GlobalAdvisorAdapterRegistry为单例模式
AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
Advisor[] var8 = config.getAdvisors();
int var9 = var8.length;

for(int var10 = 0; var10 < var9; ++var10) {
Advisor advisor = var8[var10];
MethodInterceptor[] interceptors1;
if(advisor instanceof PointcutAdvisor) {
PointcutAdvisor var20 = (PointcutAdvisor)advisor;
if(config.isPreFiltered() || var20.getPointcut().getClassFilter().matches(actualClass)) {
interceptors1 = registry.getInterceptors(advisor);
MethodMatcher mm = var20.getPointcut().getMethodMatcher();
if(MethodMatchers.matches(mm, method, actualClass, hasIntroductions)) {
if(mm.isRuntime()) {
MethodInterceptor[] var15 = interceptors1;
int var16 = interceptors1.length;

for(int var17 = 0; var17 < var16; ++var17) {
MethodInterceptor interceptor = var15[var17];
interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
}
} else {
interceptorList.addAll(Arrays.asList(interceptors1));
}
}
}
} else if(advisor instanceof IntroductionAdvisor) {
IntroductionAdvisor var19 = (IntroductionAdvisor)advisor;
if(config.isPreFiltered() || var19.getClassFilter().matches(actualClass)) {
interceptors1 = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors1));
}
} else {
MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}

return interceptorList;
}


GlobalAdvisorAdapterRegistry:

public abstract class GlobalAdvisorAdapterRegistry {
// 单例模式
private static AdvisorAdapterRegistry instance = new DefaultAdvisorAdapterRegistry();

// 适配器,返回单例适配器注册器
public GlobalAdvisorAdapterRegistry() {
}

public static AdvisorAdapterRegistry getInstance() {
return instance;
}

static void reset() {
instance = new DefaultAdvisorAdapterRegistry();
}
}


DefaultAdvisorAdapterRegistry :

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.aop.framework.adapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.adapter.AdvisorAdapter;
import org.springframework.aop.framework.adapter.AdvisorAdapterRegistry;
import org.springframework.aop.framework.adapter.AfterReturningAdviceAdapter;
import org.springframework.aop.framework.adapter.MethodBeforeAdviceAdapter;
import org.springframework.aop.framework.adapter.ThrowsAdviceAdapter;
import org.springframework.aop.framework.adapter.UnknownAdviceTypeException;
import org.springframework.aop.support.DefaultPointcutAdvisor;

public class DefaultAdvisorAdapterRegistry implements AdvisorAdapterRegistry, Serializable {
// AdvisorAdapter列表,包含MethodBeforeAdvice、MethodAfterAdvice等等
private final List<AdvisorAdapter> adapters = new ArrayList(3);

public DefaultAdvisorAdapterRegistry() {
this.registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
this.registerAdvisorAdapter(new AfterReturningAdviceAdapter());
this.registerAdvisorAdapter(new ThrowsAdviceAdapter());
}

public Advisor wrap(Object adviceObject) throws UnknownAdviceTypeException {
if(adviceObject instanceof Advisor) {
return (Advisor)adviceObject;
} else if(!(adviceObject instanceof Advice)) {
throw new UnknownAdviceTypeException(adviceObject);
} else {
Advice advice = (Advice)adviceObject;
if(advice instanceof MethodInterceptor) {
return new DefaultPointcutAdvisor(advice);
} else {
Iterator var3 = this.adapters.iterator();

AdvisorAdapter adapter;
do {
if(!var3.hasNext()) {
throw new UnknownAdviceTypeException(advice);
}

adapter = (AdvisorAdapter)var3.next();
} while(!adapter.supportsAdvice(advice));

return new DefaultPointcutAdvisor(advice);
}
}
}

public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
ArrayList interceptors = new ArrayList(3);
Advice advice = advisor.getAdvice();
if(advice instanceof MethodInterceptor) {
// 如果是MethodInterceptor,不需要适配,直接加入列表
interceptors.add((MethodInterceptor)advice);
}

Iterator var4 = this.adapters.iterator();

while(var4.hasNext()) {
AdvisorAdapter adapter = (AdvisorAdapter)var4.next();
if(adapter.supportsAdvice(advice)) {
// 遍历MethodBeforeAdviceAdapter,AfterReturningAdviceAdapter列表,看看是否适配,适配则加入拦截器链
interceptors.add(adapter.getInterceptor(advisor));
}
}

if(interceptors.isEmpty()) {
throw new UnknownAdviceTypeException(advisor.getAdvice());
} else {
return (MethodInterceptor[])interceptors.toArray(new MethodInterceptor[interceptors.size()]);
}
}

public void registerAdvisorAdapter(AdvisorAdapter adapter) {
this.adapters.add(adapter);
}
}

class AfterReturningAdviceAdapter implements AdvisorAdapter, Serializable {
AfterReturningAdviceAdapter() {
}

public boolean supportsAdvice(Advice advice) {
// 直接判断类型
return advice instanceof AfterReturningAdvice;
}

public MethodInterceptor getInterceptor(Advisor advisor) {
AfterReturningAdvice advice = (AfterReturningAdvice)advisor.getAdvice();
return new AfterReturningAdviceInterceptor(advice);
}
}


ThrowsAdviceInterceptor :

public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice {

....
public Object invoke(MethodInvocation mi) throws Throwable {
try {
return mi.proceed();
} catch (Throwable var4) {
Method handlerMethod = this.getExceptionHandler(var4);
if(handlerMethod != null) {
this.invokeHandlerMethod(mi, var4, handlerMethod);
}

throw var4;
}
}
...
}


Proxy:

通过JDK或者CGLIB的动态代理策略,生成AopProxy,得到拦截器链后,先遍历拦截器链然后才进行对实体指定方法的执行。而Advisor通知器也正因为拦截器链的存在才能起作用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: