相关背景及资源:html
曹工说Spring Boot源码(1)-- Bean Definition究竟是什么,附spring思惟导图分享java
曹工说Spring Boot源码(2)-- Bean Definition究竟是什么,我们对着接口,逐个方法讲解git
曹工说Spring Boot源码(3)-- 手动注册Bean Definition不比游戏好玩吗,咱们来试一下spring
曹工说Spring Boot源码(4)-- 我是怎么自定义ApplicationContext,从json文件读取bean definition的?express
曹工说Spring Boot源码(5)-- 怎么从properties文件读取beanapache
曹工说Spring Boot源码(6)-- Spring怎么从xml文件里解析bean的json
曹工说Spring Boot源码(7)-- Spring解析xml文件,到底从中获得了什么(上)api
曹工说Spring Boot源码(8)-- Spring解析xml文件,到底从中获得了什么(util命名空间)缓存
曹工说Spring Boot源码(9)-- Spring解析xml文件,到底从中获得了什么(context命名空间上)数据结构
曹工说Spring Boot源码(10)-- Spring解析xml文件,到底从中获得了什么(context:annotation-config 解析)
曹工说Spring Boot源码(11)-- context:component-scan,你真的会用吗(此次来讲说它的奇技淫巧)
曹工说Spring Boot源码(12)-- Spring解析xml文件,到底从中获得了什么(context:component-scan完整解析)
曹工说Spring Boot源码(13)-- AspectJ的运行时织入(Load-Time-Weaving),基本内容是讲清楚了(附源码)
曹工说Spring Boot源码(14)-- AspectJ的Load-Time-Weaving的两种实现方式细细讲解,以及怎么和Spring Instrumentation集成
曹工说Spring Boot源码(15)-- Spring从xml文件里到底获得了什么(context:load-time-weaver 完整解析)
曹工说Spring Boot源码(16)-- Spring从xml文件里到底获得了什么(aop:config完整解析【上】)
曹工说Spring Boot源码(17)-- Spring从xml文件里到底获得了什么(aop:config完整解析【中】)
曹工说Spring Boot源码(18)-- Spring AOP源码分析三部曲,终于快讲完了 (aop:config完整解析【下】)
曹工说Spring Boot源码(19)-- Spring 带给咱们的工具利器,建立代理不用愁(ProxyFactory)
曹工说Spring Boot源码(20)-- 码网恢恢,疏而不漏,如何记录Spring RedisTemplate每次操做日志
曹工说Spring Boot源码(21)-- 为了让你们理解Spring Aop利器ProxyFactory,我已经拼了
工程结构图:
本讲,主要讲讲,spring aop和aspectJ到底啥关系,若是说spring aop依赖aspectJ,那么,究竟是哪儿依赖它了?
得讲证据啊,对不对?
其实,我能够先说下结论。spring aop是基于代理的,有接口的时候,就是基于jdk 动态代理,jdk动态代理是只能对方法进行代理的,由于在Proxy.newInstance建立代理时,传入的第三个参数为java.lang.reflect.InvocationHandler,该接口只有一个方法:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
这里面的method,就是被调用的方法,因此,jdk动态代理,是只能对方法进行代理。
而aspectJ就要强大多了,能够对field、constructor的访问进行拦截;并且,spring aop的采用运行期间去生成目标对象的代理对象来实现,致使其只能在运行期工做。
而咱们知道,AspectJ是能够在编译期经过特殊的编译期,就把切面逻辑,织入到class中,并且能够嵌入切面逻辑到任意地方,好比constructor、静态初始化块、field的set/get等;
另外,AspectJ也支持LTW,前面几讲咱们讲过这个东西,即在jvm加载class的时候,去修改class字节码。
AspectJ也无心去搞运行期织入,Spring aop也无心去搞编译期和类加载期织入说了半天,spring aop看起来和AspectJ没半点交集啊,可是,他们真的毫无关系吗?
我打开了ide里,spring-aop-5.1.9.RELEASE的pom文件,里面清楚看到了
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.1.9.RELEASE</version> <name>Spring AOP</name> ... <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.1.9.RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.1.9.RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.jamonapi</groupId> <artifactId>jamon</artifactId> <version>2.81</version> <scope>compile</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.6.0</version> <scope>compile</scope> <optional>true</optional> </dependency> // 就是这里 <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> <scope>compile</scope> <optional>true</optional> </dependency> </dependencies> </project>
因此,你们看到,spring aop依赖了aspectjweaver。到底为何依赖它,就是咱们本节的主题。
在此以前,咱们先简单了解下AspectJ。
假设我有以下类:
package foo; public interface Perform { public void sing(); }
而后,咱们再用AspectJ的方式来定义一个切点:
execution(public * *.Perform.sing(..))
你们一看,确定知道,这个切点是能够匹配这个Perform类的sing方法的,可是,若是让你用程序实现呢?你怎么作?
我据说Spring最先的时候,是不依赖AspectJ的,本身写正则来完成上面的判断是否匹配切点的逻辑,但后来,不知道为啥,就变成了AspectJ了。
若是咱们要用AspectJ来判断,有几步?
maven的pom里,只须要引入以下依赖:
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.2</version> </dependency>
private static final Set<PointcutPrimitive> SUPPORTED_PRIMITIVES = new HashSet<PointcutPrimitive>(); static { SUPPORTED_PRIMITIVES.add(PointcutPrimitive.EXECUTION); SUPPORTED_PRIMITIVES.add(PointcutPrimitive.ARGS); SUPPORTED_PRIMITIVES.add(PointcutPrimitive.REFERENCE); SUPPORTED_PRIMITIVES.add(PointcutPrimitive.THIS); SUPPORTED_PRIMITIVES.add(PointcutPrimitive.TARGET); SUPPORTED_PRIMITIVES.add(PointcutPrimitive.WITHIN); SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_ANNOTATION); SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_WITHIN); SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_ARGS); SUPPORTED_PRIMITIVES.add(PointcutPrimitive.AT_TARGET); } #下面这个方法,就是来获取切点解析器的,cl是一个classloader类型的实例 /** * Initialize the underlying AspectJ pointcut parser. */ private static PointcutParser initializePointcutParser(ClassLoader cl) { PointcutParser parser = PointcutParser .getPointcutParserSupportingSpecifiedPrimitivesAndUsingSpecifiedClassLoaderForResolution( SUPPORTED_PRIMITIVES, cl); return parser; }
你们能够看到,要得到PointcutParser的实例,只须要调用其一个静态方法,这个静态方法虽然很长,但仍是很好读的,读完基本知道方法啥意思了:获取一个利用指定classloader、支持指定的原语集合的切点解析器。
咱们定义了一个集合,集合里塞了一堆集合,这些集合是什么呢?我简单摘抄了几个:
位于org.aspectj.weaver.tools.PointcutPrimitive类: public static final PointcutPrimitive CALL = new PointcutPrimitive("call",1); public static final PointcutPrimitive EXECUTION = new PointcutPrimitive("execution",2); public static final PointcutPrimitive GET = new PointcutPrimitive("get",3); public static final PointcutPrimitive SET = new PointcutPrimitive("set",4); public static final PointcutPrimitive INITIALIZATION = new PointcutPrimitive("initialization",5);
其实,这些就是表明了切点中的一些语法原语,SUPPORTED_PRIMITIVES这个集合,就是加了一堆原语,从SUPPORTED_PRIMITIVES的名字能够看出,就是说:我支持解析哪些切点。
你们知道,切点表达式里是以下结构:public/private 返回值 包名.类名.方法名(参数...);这里面的类名部分,若是明确指定了,是须要去加载这个class的。这个cl就是用于加载切点中的类型部分。
原注释以下:
* When resolving types in pointcut expressions, the given classloader is used to find types.
这里有个比较有意思的部分,在生成的PointcutParser实例中,是怎么保存这个classloader的呢?
private WeakClassLoaderReference classLoaderReference; /** * Set the classloader that this parser should use for type resolution. * * @param aLoader */ protected void setClassLoader(ClassLoader aLoader) { this.classLoaderReference = new WeakClassLoaderReference(aLoader); world = new ReflectionWorld(this.classLoaderReference.getClassLoader()); }
能够看到,进来的classloader,做为构造器参数,new了一个WeakClassLoaderReference实例。
public class WeakClassLoaderReference{ protected final int hashcode; //1. 重点关注处 private final WeakReference loaderRef; public WeakClassLoaderReference(ClassLoader loader) { loaderRef = new WeakReference(loader); if(loader == null){ // Bug: 363962 // Check that ClassLoader is not null, for instance when loaded from BootStrapClassLoader hashcode = System.identityHashCode(this); }else{ hashcode = loader.hashCode() * 37; } } public ClassLoader getClassLoader() { ClassLoader instance = (ClassLoader) loaderRef.get(); // Assert instance!=null return instance; } }
上面的讲解点1,你们看到,使用了弱引用来保存,我说下缘由,主要是为了不在应用上层已经销毁了该classloader加载的全部实例、全部Class,准备回收该classloader的时候,却由于PointcutParser长期持有该classloader的引用,致使无法垃圾回收。
/** * Build the underlying AspectJ pointcut expression. */ private static PointcutExpression buildPointcutExpression(ClassLoader classLoader, String expression) { PointcutParser parser = initializePointcutParser(classLoader); // 讲解点1 return parser.parsePointcutExpression(expression); }
讲解点1,就是目前所在位置。咱们拿到切点表达式后,利用parser.parsePointcutExpression(expression)
解析,返回的对象为PointcutExpression类型。
public static void main(String[] args) throws NoSuchMethodException { boolean b = testClassMatchExpression("execution(public * foo.Perform.*(..))", Performer.class); System.out.println(b); b = testClassMatchExpression("execution(public * foo.Perform.*(..))", Main.class); System.out.println(b); b = testClassMatchExpression("execution(public * foo.Perform.*(..))", Perform.class); System.out.println(b); } /** * 测试class匹配 * @param expression * @param clazzToBeTest * @return */ public static boolean testClassMatchExpression(String expression, Class<?> clazzToBeTest) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); PointcutExpression pointcutExpression = buildPointcutExpression(classLoader, expression); boolean b = pointcutExpression.couldMatchJoinPointsInType(clazzToBeTest); return b; }
输出以下:
true Performer实现了Perform接口,全部匹配
false Main类,固然不能匹配
true 彻底匹配
说完了class匹配,下面咱们看看怎么实现方法匹配。
方法匹配的代码也很简单,以下:
public static void main(String[] args) throws NoSuchMethodException { boolean b = testClassMatchExpression("execution(public * foo.Perform.*(..))", Performer.class); System.out.println(b); b = testClassMatchExpression("execution(public * foo.Perform.*(..))", Main.class); System.out.println(b); b = testClassMatchExpression("execution(public * foo.Perform.*(..))", Perform.class); System.out.println(b); Method sing = Perform.class.getMethod("sing"); b = testMethodMatchExpression("execution(public * *.*.sing(..))",sing); System.out.println(b); } /** * 测试方法匹配 * @param expression * @return */ public static boolean testMethodMatchExpression(String expression, Method targetMethod) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); PointcutExpression pointcutExpression = buildPointcutExpression(classLoader, expression); ShadowMatch shadowMatch = pointcutExpression.matchesMethodExecution(targetMethod); if (shadowMatch.alwaysMatches()) { return true; } else if (shadowMatch.neverMatches()) { return false; } else if (shadowMatch.maybeMatches()) { System.out.println("可能匹配"); } return false; }
主要是这个方法:
ShadowMatch shadowMatch = pointcutExpression.matchesMethodExecution(targetMethod);
返回的shadowMatch类型实例,这个是个接口,专门用来表示:切点匹配后的结果。其注释以下:
/** * The result of asking a PointcutExpression to match at a shadow (method execution, * handler, constructor call, and so on). * */
其有以下几个方法:
public interface ShadowMatch { /** * True iff the pointcut expression will match any join point at this * shadow (for example, any call to the given method). */ boolean alwaysMatches(); /** * True if the pointcut expression may match some join points at this * shadow (for example, some calls to the given method may match, depending * on the type of the caller). * <p>If alwaysMatches is true, then maybeMatches is always true.</p> */ boolean maybeMatches(); /** * True iff the pointcut expression can never match any join point at this * shadow (for example, the pointcut will never match a call to the given * method). */ boolean neverMatches(); ... }
这个接口就是告诉你,匹配了切点后,你能够找它拿结果,结果多是:老是匹配;老是不匹配;可能匹配。
什么状况下,会返回可能匹配,我目前还没试验出来。
我跟过AspectJ的代码,发现解析处主要在如下方法:
org.aspectj.weaver.patterns.SignaturePattern#matchesExactlyMethod
有兴趣的小伙伴能够看下,方法很长,如下只是一部分。
private FuzzyBoolean matchesExactlyMethod(JoinPointSignature aMethod, World world, boolean subjectMatch) { if (parametersCannotMatch(aMethod)) { // System.err.println("Parameter types pattern " + parameterTypes + " pcount: " + aMethod.getParameterTypes().length); return FuzzyBoolean.NO; } // OPTIMIZE only for exact match do the pattern match now? Otherwise defer it until other fast checks complete? if (!name.matches(aMethod.getName())) { return FuzzyBoolean.NO; } // Check the throws pattern if (subjectMatch && !throwsPattern.matches(aMethod.getExceptions(), world)) { return FuzzyBoolean.NO; } // '*' trivially matches everything, no need to check further if (!declaringType.isStar()) { if (!declaringType.matchesStatically(aMethod.getDeclaringType().resolve(world))) { return FuzzyBoolean.MAYBE; } } ... }
这两部分,代码就讲到这里了。个人demo源码在:
前面为何要讲AspectJ如何进行切点匹配呢?
由于,就我所知的,就有好几处Spring Aop依赖AspectJ的例子:
spring 实现的ltw,org.springframework.context.weaving.AspectJWeavingEnabler里面依赖了org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter,这个是ltw的范畴,和今天的讲解其实关系不大,有兴趣能够去翻本系列的ltw相关的几篇;
org.springframework.aop.aspectj.AspectJExpressionPointcut,这个是重头,目前的spring aop,咱们写的切点表达式,最后就是在内部用该数据结构来保存;
你们若是仔细看ComponentScan注解,里面有个filter字段,可让你自定义要扫描哪些类,filter有个类型字段,分别有以下几种枚举值:
/** * Specifies which types are eligible for component scanning. */ Filter[] includeFilters() default {}; /** * Specifies which types are not eligible for component scanning. * @see #resourcePattern */ Filter[] excludeFilters() default {}; /** * Declares the type filter to be used as an {@linkplain ComponentScan#includeFilters * include filter} or {@linkplain ComponentScan#excludeFilters exclude filter}. */ @Retention(RetentionPolicy.RUNTIME) @Target({}) @interface Filter { /** * The type of filter to use. * <p>Default is {@link FilterType#ANNOTATION}. * @see #classes * @see #pattern */ // 讲解点1 FilterType type() default FilterType.ANNOTATION; ... /** * The pattern (or patterns) to use for the filter, as an alternative * to specifying a Class {@link #value}. * <p>If {@link #type} is set to {@link FilterType#ASPECTJ ASPECTJ}, * this is an AspectJ type pattern expression. If {@link #type} is * set to {@link FilterType#REGEX REGEX}, this is a regex pattern * for the fully-qualified class names to match. * @see #type * @see #classes */ String[] pattern() default {}; }
其中,讲解点1,能够看到,里面默认是ANNOTATION类型,实际还有其余类型;
讲解点2,若是type选择ASPECTJ,则这里写AspectJ语法的切点表达式便可。
public enum FilterType { /** * Filter candidates marked with a given annotation. * @see org.springframework.core.type.filter.AnnotationTypeFilter */ ANNOTATION, /** * Filter candidates assignable to a given type. * @see org.springframework.core.type.filter.AssignableTypeFilter */ ASSIGNABLE_TYPE, /** * 讲解点1 * Filter candidates matching a given AspectJ type pattern expression. * @see org.springframework.core.type.filter.AspectJTypeFilter */ ASPECTJ, /** * Filter candidates matching a given regex pattern. * @see org.springframework.core.type.filter.RegexPatternTypeFilter */ REGEX, /** Filter candidates using a given custom * {@link org.springframework.core.type.filter.TypeFilter} implementation. */ CUSTOM }
纵观以上几点,能够发现,Spring Aop集成AspectJ,只是把切点这一套语法、@Aspect这类注解、切点的解析,都直接使用AspectJ的,没有本身另起炉灶。可是核心呢,是没有使用AspectJ的编译期注入和ltw的。
下面咱们仔细讲解,上面的第二点,这也是最重要的一点。
这里不会讲aop的实现流程,你们能够去翻前面几篇,从这篇往下的几篇。
曹工说Spring Boot源码(16)-- Spring从xml文件里到底获得了什么(aop:config完整解析【上】)
在aop解析xml或者@Aspect时,最终切点是用AspectJExpressionPointcut 类型来表示的,且被注册到了ioc容器,后续能够经过getBean直接获取该切点
在AspectJAwareAdvisorAutoProxyCreator 这个BeanPostProcessor对target进行处理时,会先判断该target是否须要生成代理,此时,就会使用到咱们前面讲解的东西。
判断该target是否匹配切点,若是匹配,则生成代理;不然不生成。
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { ... // 获取可以匹配该target bean的拦截器,即aspect切面 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; }
咱们主要看getAdvicesAndAdvisorsForBean:
@Override protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource targetSource) { List advisors = findEligibleAdvisors(beanClass, beanName); if (advisors.isEmpty()) { return DO_NOT_PROXY; } return advisors.toArray(); } protected List<Advisor> findEligibleAdvisors(Class beanClass, String beanName) { // 讲解点1 List<Advisor> candidateAdvisors = findCandidateAdvisors(); // 讲解点2 List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); return eligibleAdvisors; }
讲解点1,获取所有的切面集合;
讲解点2,过滤出可以匹配target bean的切面集合
protected List<Advisor> findAdvisorsThatCanApply( List<Advisor> candidateAdvisors, Class beanClass, String beanName) { ProxyCreationContext.setCurrentProxiedBeanName(beanName); try { return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass); } finally { ProxyCreationContext.setCurrentProxiedBeanName(null); } }
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) { if (candidateAdvisors.isEmpty()) { return candidateAdvisors; } for (Advisor candidate : candidateAdvisors) { // canApply就是判断切面和target的class是否匹配 if (canApply(candidate, clazz)) { eligibleAdvisors.add(candidate); } } return eligibleAdvisors; }
因此,重点就来到了canApply方法:
public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) { if (advisor instanceof PointcutAdvisor) { PointcutAdvisor pca = (PointcutAdvisor) advisor; //讲解点1 return canApply(pca.getPointcut(), targetClass); } else { // It doesn't have a pointcut so we assume it applies. return true; } }
讲解点1,就是首先pca.getPointcut()获取了切点,而后调用了以下方法:
org.springframework.aop.support.AopUtils#canApply public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) { //讲解点1 if (!pc.getClassFilter().matches(targetClass)) { return false; } MethodMatcher methodMatcher = pc.getMethodMatcher(); // 讲解点2 Set<Class> classes = new HashSet<Class>(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); classes.add(targetClass); for (Class<?> clazz : classes) { Method[] methods = clazz.getMethods(); for (Method method : methods) { // 讲解点3 if (methodMatcher.matches(method, targetClass)) { return true; } } } return false; }
这里,其实就是使用Pointcut来匹配target class了。具体两个过程:
因此,匹配切点的工做,落在了
methodMatcher.matches(method, targetClass)
由于,AspectJExpressionPointcut 这个类,本身实现了MethodMatcher,因此,上面的methodMatcher.matches(method, targetClass)
实现逻辑,其实就在:
org.springframework.aop.aspectj.AspectJExpressionPointcut#matches
咱们只要看它怎么来实现matches方法便可。
public boolean matches(Method method, Class targetClass, boolean beanHasIntroductions) { checkReadyToMatch(); Method targetMethod = AopUtils.getMostSpecificMethod(method, targetClass); ShadowMatch shadowMatch = getShadowMatch(targetMethod, method); if (shadowMatch.alwaysMatches()) { return true; } else if (shadowMatch.neverMatches()) { return false; } else { // the maybe case return (beanHasIntroductions || matchesIgnoringSubtypes(shadowMatch) || matchesTarget(shadowMatch, targetClass)); } } private ShadowMatch getShadowMatch(Method targetMethod, Method originalMethod) { // 讲解点1 ShadowMatch shadowMatch = this.shadowMatchCache.get(targetMethod); if (shadowMatch == null) { synchronized (this.shadowMatchCache) { // Not found - now check again with full lock... Method methodToMatch = targetMethod; shadowMatch = this.shadowMatchCache.get(methodToMatch); if (shadowMatch == null) { // 讲解点2 shadowMatch = this.pointcutExpression.matchesMethodExecution(targetMethod); if (shadowMatch.maybeMatches() && fallbackPointcutExpression!=null) { shadowMatch = new DefensiveShadowMatch(shadowMatch, fallbackPointcutExpression.matchesMethodExecution(methodToMatch)); } //讲解点3 this.shadowMatchCache.put(targetMethod, shadowMatch); } } } return shadowMatch; }
这里三个讲解点。
至于其pointcutExpression的生成,这个和AspectJ的相似,就不说了。
假设,通过上述步骤,咱们生成了代理,这里假设为jdk动态代理类型,其最终的动态代理对象的invocationHandler类以下:
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler
其invoke方法内:
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; target = targetSource.getTarget(); // 讲解点1 List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); // Check whether we have any advice. If we don't, we can fallback on direct // reflective invocation of the target, and avoid creating a MethodInvocation. if (chain.isEmpty()) { retVal = AopUtils.invokeJoinpointUsingReflection(target, method, args); } else { // We need to create a method invocation... invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain); // Proceed to the joinpoint through the interceptor chain. retVal = invocation.proceed(); } return retVal; } }
咱们只关注讲解点,这里讲解点1:获取匹配目标方法和class的拦截器链。
public List<Object> getInterceptorsAndDynamicInterceptionAdvice( Advised config, Method method, Class targetClass) { List<Object> interceptorList = new ArrayList<Object>(config.getAdvisors().length); boolean hasIntroductions = hasMatchingIntroductions(config, targetClass); AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance(); for (Advisor advisor : config.getAdvisors()) { if (advisor instanceof PointcutAdvisor) { // Add it conditionally. PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor; // 讲解点1 if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(targetClass)) { MethodInterceptor[] interceptors = registry.getInterceptors(advisor); //讲解点2 MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher(); //讲解点3 if (MethodMatchers.matches(mm, method, targetClass, hasIntroductions)) { if (mm.isRuntime()) { ... } else { interceptorList.addAll(Arrays.asList(interceptors)); } } } } } return interceptorList; }
三个讲解点。
但愿个人讲解,让你们看明白了,若有不明白之处,可留言,我会继续改进。
总的来讲,spring aop就是把aspectJ当个工具来用,切点语法、切点解析、还有你们经常使用的注解定义切面@Aspect、@Pointcut等等,都是aspectJ的:
org.aspectj.lang.annotation.Aspect
org.aspectj.lang.annotation.Pointcut。