- 完成AspectListExecutor類的編寫
- 完成AspectWeaver類的編寫
- 完成PointcutLocator類的編寫
- 完成ProxyCreator類的編寫
package com.wuyiccc.helloframework.aop; import org.aspectj.weaver.tools.PointcutExpression; import org.aspectj.weaver.tools.PointcutParser; import org.aspectj.weaver.tools.ShadowMatch; import java.lang.reflect.Method; /** * @author wuyiccc * @date 2020/7/14 9:03 * 豈曰無衣,與子同袍~ */ public class PointcutLocator { /** * Pointcut解析器,直接給它賦值上Aspectj的全部表達式,以便支持對衆多表達式的解析 */ private PointcutParser pointcutParser = PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution(PointcutParser.getAllSupportedPointcutPrimitives()); /** * 表達式解析器 */ private PointcutExpression pointcutExpression; public PointcutLocator(String expression) { this.pointcutExpression = pointcutParser.parsePointcutExpression(expression); } /** * 判斷傳入的Class對象是不是Aspect的目標代理類,即匹配Pointcut表達式(初篩) * * @param targetClass 目標類 * @return 是否匹配 */ public boolean roughMatches(Class<?> targetClass) { return pointcutExpression.couldMatchJoinPointsInType(targetClass); // 只能校驗within,對於execution,call,get,set等沒法校驗的表達式,直接返回true } /** * 判斷傳入的Method對象是不是Aspect的目標代理方法,即匹配Pointcut表達式(精篩) * @param method * @return */ public boolean accurateMatches(Method method) { ShadowMatch shadowMatch = pointcutExpression.matchesMethodExecution(method); if (shadowMatch.alwaysMatches()) { return true; } return false; } }
package com.wuyiccc.helloframework.aop; import com.wuyiccc.helloframework.aop.aspect.AspectInfo; import com.wuyiccc.helloframework.util.ValidationUtil; import lombok.Getter; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * @author wuyiccc * @date 2020/7/14 9:03 * 豈曰無衣,與子同袍~ */ public class AspectListExecutor implements MethodInterceptor { private Class<?> targetClass; @Getter private List<AspectInfo> sortedAspectInfoList; public AspectListExecutor(Class<?> targetClass, List<AspectInfo> sortedAspectInfoList) { this.targetClass = targetClass; this.sortedAspectInfoList = sortAspectInfoList(sortedAspectInfoList); } /** * 按照order的值進行升序排序,確保Order值小的aspect先被織入 * * @param aspectInfoList * @return */ private List<AspectInfo> sortAspectInfoList(List<AspectInfo> aspectInfoList) { // 升序排列 Collections.sort(aspectInfoList, new Comparator<AspectInfo>() { @Override public int compare(AspectInfo o1, AspectInfo o2) { return o1.getOrderIndex() - o2.getOrderIndex(); } }); return aspectInfoList; } @Override public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { Object returnValue = null; collectAccurateMatchedAspectList(method); if (ValidationUtil.isEmpty(sortedAspectInfoList)) { return methodProxy.invokeSuper(proxy, args); } // 1. 按照order的順序升序執行完全部Aspect的before方法 invokeBeforeAdvices(method, args); try { // 2. 執行被代理類的方法 returnValue = methodProxy.invokeSuper(proxy, args); // 3. 若是被代理方法正常返回,則按照order的順序降序執行完全部Aspect的afterReturning方法 invokeAfterReturningAdvices(method, args, returnValue); } catch (Exception e) { // 4. 若是被代理方法拋出異常,則按照order的順序降序執行完全部Aspect的afterThrowing方法 invokeAfterThrowingAdvices(method, args, e); } return returnValue; } private void collectAccurateMatchedAspectList(Method method) { if (ValidationUtil.isEmpty(sortedAspectInfoList)) { return; } Iterator<AspectInfo> it = sortedAspectInfoList.iterator(); while (it.hasNext()) { AspectInfo aspectInfo = it.next(); if (!aspectInfo.getPointcutLocator().accurateMatches(method)) { it.remove(); // 須要用Iterator自帶的remove,不能用sortedAspectInfoList的remove,不然就會出現併發修改異常 } } } private void invokeAfterThrowingAdvices(Method method, Object[] args, Exception e) throws Throwable { for (int i = sortedAspectInfoList.size() - 1; i >= 0; i--) { sortedAspectInfoList.get(i).getAspectObject().afterThrowing(targetClass, method, args, e); } } private void invokeAfterReturningAdvices(Method method, Object[] args, Object returnValue) throws Throwable { for (int i = sortedAspectInfoList.size() - 1; i >= 0; i--) { sortedAspectInfoList.get(i).getAspectObject().afterReturning(targetClass, method, args, returnValue); } } private void invokeBeforeAdvices(Method method, Object[] args) throws Throwable { for (AspectInfo aspectInfo : sortedAspectInfoList) { aspectInfo.getAspectObject().before(targetClass, method, args); } } }
package org.myframework.aop; import org.myframework.aop.annotation.Aspect; import org.myframework.aop.annotation.Order; import org.myframework.aop.aspect.AspectInfo; import org.myframework.aop.aspect.DefaultAspect; import org.myframework.core.BeanContainer; import org.myframework.util.ValidationUtil; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * @author wuyiccc * @date 2020/6/16 8:49 * 豈曰無衣,與子同袍~ */ public class AspectWeaver { private BeanContainer beanContainer; public AspectWeaver() { beanContainer = BeanContainer.getInstance(); } public void doAop() { // 1. 獲取全部的切面類 Set<Class<?>> aspectSet = beanContainer.getClassesByAnnotation(Aspect.class); if (ValidationUtil.isEmpty(aspectSet)) { return; } // 2. 拼裝AspectInfoList List<AspectInfo> aspectInfoList = packAspectInfoList(aspectSet); // 3. 遍歷容器裏的類 Set<Class<?>> classSet = beanContainer.getClasses(); for (Class<?> targetClass : classSet) { // 排除AspectClass自身 if (targetClass.isAnnotationPresent(Aspect.class)) { continue; } // 4. 粗篩符和條件的Aspect List<AspectInfo> roughMatchedAspectList = collectRoughMatchAspectListForSpecificClass(aspectInfoList, targetClass); // 5. 嘗試進行Aspect織入 wrapIfNecessary(roughMatchedAspectList, targetClass); } } private void wrapIfNecessary(List<AspectInfo> roughMatchedAspectList, Class<?> targetClass) { if (ValidationUtil.isEmpty(roughMatchedAspectList)) { return; } // 建立動態代理對象 AspectListExecutor aspectListExecutor = new AspectListExecutor(targetClass, roughMatchedAspectList); Object proxyBean = ProxyCreator.createProxy(targetClass, aspectListExecutor); beanContainer.addBean(targetClass, proxyBean); } private List<AspectInfo> collectRoughMatchAspectListForSpecificClass(List<AspectInfo> aspectInfoList, Class<?> targetClass) { List<AspectInfo> roughMatchedAspectList = new ArrayList<>(); for (AspectInfo aspectInfo : aspectInfoList) { // 粗篩 if (aspectInfo.getPointcutLocator().roughMatches(targetClass)) { roughMatchedAspectList.add(aspectInfo); } } return roughMatchedAspectList; } private List<AspectInfo> packAspectInfoList(Set<Class<?>> aspectSet) { List<AspectInfo> aspectInfoList = new ArrayList<>(); for (Class<?> aspectClass : aspectSet) { if (verifyAspect(aspectClass)) { Order orderTag = aspectClass.getAnnotation(Order.class); Aspect aspectTag = aspectClass.getAnnotation(Aspect.class); DefaultAspect defaultAspect = (DefaultAspect) beanContainer.getBean(aspectClass); // 初始化表達式定位器 PointcutLocator pointcutLocator = new PointcutLocator(aspectTag.pointcut()); AspectInfo aspectInfo = new AspectInfo(orderTag.value(), defaultAspect, pointcutLocator); aspectInfoList.add(aspectInfo); } else { throw new RuntimeException("@Aspect and @Order must be added to the Aspect class, and Aspect class must extend from DefaultAspect"); } } return aspectInfoList; } // 框架中必定要遵照給Aspect添加的@Aspect和@Order標籤的規範,同時,必須繼承自DefaultAspect.class private boolean verifyAspect(Class<?> aspectClass) { return aspectClass.isAnnotationPresent(Aspect.class) && aspectClass.isAnnotationPresent(Order.class) && DefaultAspect.class.isAssignableFrom(aspectClass); } }
github地址:https://github.com/wuyiccc/he...java