AOP是拦截的方法后要作对应的织入,那么先定义几种通知:前置通知、后置通知、异常通知、结束通知,代码以下:java
public interface AopAdvice { public void before(Proxy proxy); public void after(Proxy proxy); public void exception(Proxy proxy); public void end(Proxy proxy); }
接下来看,哪些类里的哪些方法要被拦截呢?咱们须要定义一个表达式,这么使用正则表达式,相对来讲比较简单,也是一个通用的规范。只有配到正则的方法,才会执行对应织入的加强。git
@Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface Aspect { public String classRegex(); public String beforeRegex() default ""; public String afterRegex() default ""; public String exceptionRegex() default ""; public String endRegex() default ""; public int order() default 0; }
classRegex定义要拦截的class正则正则表达式
beforeRegex定义须要前置加强的方法的正则匹配设计模式
afterRegex定义须要后置加强的方法的正则匹配app
exceptionRegex定义须要进行异常处理加强方法的正则匹配框架
endRegex定义在方法执行完成以后须要额外处理方法的正则匹配dom
order表示排序,有多个aop规则命中时,就须要排序,这里是升序排列,order越大,该aop越靠后执行ide
AOP实现的本质是动态代理,那么咱们须要定义一个代理接口工具
public interface Proxy { public void invoke(Proxy proxy) throws Throwable; }
这个接口里定义了一个方法invoke(Proxy proxy),参数是它本身,那么什么这样定义呢?这里就要谈到一种设计模式“责任链”,因为被cglib代理过的类不能再次被代理,因此这里才用责任链模式来解决。具体来看责任链在这里怎么运做的。this
public class BeanProxy implements Proxy { private Object obj; private Object[] args; private Method method; private MethodProxy methodProxy; private boolean invokeSuper = true; private int proxyIndex = -1; private Object result = null; private InterfaceExecutor interfaceExecutor; private List<Proxy> proxyList = new ArrayList<Proxy>(); public BeanProxy() { } public BeanProxy(Object obj, Object[] args, Method method, MethodProxy methodProxy) { this.obj = obj; this.args = args; this.method = method; this.methodProxy = methodProxy; } @Override public void invoke(Proxy proxy) throws Throwable { proxyIndex++; if (proxyIndex < proxyList.size()) { proxyList.get(proxyIndex).invoke(this); } else if (invokeSuper) { result = methodProxy.invokeSuper(obj, args); } else { result = interfaceExecutor.invoke(obj, method, args, methodProxy); } } public BeanProxy addProxyChain(Proxy proxy) { proxyList.add(proxy); return this; } public BeanProxy setInterfaceExecutor(InterfaceExecutor interfaceExecutor) { this.interfaceExecutor = interfaceExecutor; return this; } ………………省略了一些set方法 }
BeanProxy实现了invoke方法,上游节点将调用权给下游节点,直到指针指向链的末尾,当指针指向链尾端是,若是设置的invokeSuper为true(invokeSuper表示是否执行被代理的父类方法),则执行父类方法,若是父类方法是接口,则必定要设置为false。在《TeaFramework——ORM框架的实现(一)》留了一个InterfaceExecutor的疑问,InterfaceExecutor是专门为被代理的类是接口的场景准备的,当被代理的类为接口,可是又想执行一些本来想实现的额外操做,就能够用InterfaceExecutor来实现,例如ORM中OrmProxy就是一个典型的例子。
特别说明:对于链式调用,invoke方法以前的方法是正序调用,invoke方法以后是逆序。这一点和全部责任链调用过程一致,例如Filter、Struts2的拦截等。
对于AOP代理,TeaFramework中实现了一个抽象代理类,要编写本身的AOP只需继承这个抽象类,实现对应的前置、后置等方法。
public abstract class AbstractProxy implements Proxy, AopAdvice { private Pattern beforePattern; private Pattern afterPattern; private Pattern exceptionPattern; private Pattern endPattern; @Override public void invoke(Proxy proxy) throws Throwable { BeanProxy beanProxy = (BeanProxy) proxy; try { if (beforePattern != null && beforePattern.matcher(beanProxy.getMethod().getName()).find()) { before(proxy); } proxy.invoke(proxy); if (afterPattern != null && afterPattern.matcher(beanProxy.getMethod().getName()).find()) { after(proxy); } } catch (Throwable e) { if (exceptionPattern != null && exceptionPattern.matcher(beanProxy.getMethod().getName()).find()) { exception(proxy); } throw e; } finally { if (endPattern != null && endPattern.matcher(beanProxy.getMethod().getName()).find()) { end(beanProxy); } } } @Override public void before(Proxy proxy) { } @Override public void after(Proxy proxy) { } @Override public void exception(Proxy proxy) { } @Override public void end(Proxy proxy) { } public final void setBeforePattern(Pattern beforePattern) { this.beforePattern = beforePattern; } public final void setAfterPattern(Pattern afterPattern) { this.afterPattern = afterPattern; } public final void setExceptionPattern(Pattern exceptionPattern) { this.exceptionPattern = exceptionPattern; } public void setEndPattern(Pattern endPattern) { this.endPattern = endPattern; } }
有了这些工具,咱们就能够实现本身的AOP业务了,看个例子,比方说对应新增和修改而言,咱们须要把CCUU值填充进去,这个时候就能够用AOP了,请看下面的代码
@Aspect(classRegex = "org.teaframework.erp.*.dao.*", beforeRegex = "add.*|update.*") public class DomainAspect extends AbstractProxy { @Override public void before(Proxy proxy) { BeanProxy beanProxy = (BeanProxy) proxy; if (beanProxy.getArgs() != null && beanProxy.getArgs()[0] instanceof BaseDomain) { BaseDomain domain = (BaseDomain) beanProxy.getArgs()[0]; domain.setCreateDate(new Date()); domain.setCreateUser(ThreadVariable.getUser().getUserName()); domain.setUpdateDate(new Date()); domain.setUpdateUser(ThreadVariable.getUser().getUserName()); } } }
classRegex定义了要拦截全部dao包里的类,beforeRegex定义具体拦截add或者upate开头的方法进行前置加强织入,重写AbstractProxy的before方法便可实现前置加强了。
接下来问题来了,DomainAspect等本身实现的AOP类,怎么和bean容器的bean关联起来的呢?咱们接着看。
框架启动时,有一个AopBeanInitialization,这个类将全部加了Aspect注解的类扫描到,而后实例化,根据order升序排列,放到一个Map里。
public class AopBeanInitialization implements Initialization { public static final List<AspectClassMapping> AOP_BEAN_LIST = new ArrayList<AspectClassMapping>(); public static final Map<Class<?>, Pattern> PATTERN_MAPPING = new HashMap<Class<?>, Pattern>(); @Override public void init() throws Exception { for (String classPath : ScanPackageInitialization.classPaths) {// aop Class<?> clazz = ClassLoaderUtil.loadClass(classPath); if (clazz.isAnnotationPresent(Aspect.class)) { AbstractProxy aspectBean = (AbstractProxy) clazz.newInstance(); Aspect aspect = clazz.getAnnotation(Aspect.class); PATTERN_MAPPING.put(clazz, Pattern.compile(aspect.classRegex())); if (!"".equals(aspect.beforeRegex())) { aspectBean.setBeforePattern(Pattern.compile(aspect.beforeRegex())); } if (!"".equals(aspect.afterRegex())) { aspectBean.setAfterPattern(Pattern.compile(aspect.afterRegex())); } if (!"".equals(aspect.exceptionRegex())) { aspectBean.setExceptionPattern(Pattern.compile(aspect.exceptionRegex())); } if (!"".equals(aspect.endRegex())) { aspectBean.setEndPattern(Pattern.compile(aspect.endRegex())); } AOP_BEAN_LIST.add(new AspectClassMapping(clazz, aspectBean, aspect.order())); } } Collections.sort(AOP_BEAN_LIST, new Comparator<AspectClassMapping>() { public int compare(AspectClassMapping o1, AspectClassMapping o2) { return o2.getOrder() - o1.getOrder(); } }); } }
AopBeanInitialization执行完成以后,BeanContainerInitialization开始执行,对于命中了正则规则的类就须要动态代理了,而后将对应的AOP代理对象add到代理链中,请看下来的代码
private void addProxy(BeanProxy beanProxy, Class<?> clazz) { for (AspectClassMapping aspectClassMapping : AopBeanInitialization.AOP_BEAN_LIST) { Class<?> proxyClass = aspectClassMapping.getClazz(); Matcher matcher = AopBeanInitialization.PATTERN_MAPPING.get(proxyClass).matcher(clazz.getName()); if (matcher.find()) { beanProxy.addProxyChain(aspectClassMapping.getAspectBean()); } } if (clazz.isAnnotationPresent(Transcation.class)) { beanProxy.addProxyChain(transcationProxy); } else { Method[] methods = clazz.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(Transcation.class)) { beanProxy.addProxyChain(transcationProxy); break; } } } }
一旦AOP代理对象被放入对应的代理链中,就能够链式调用了,便发挥出了AOP的做用,上面的代码还有关于事物Transcation的代码,本篇博客先不作介绍,将会有单独的一篇博客讲事物控制的设计。
项目地址:https://git.oschina.net/lxkm/teaframework
博客:https://my.oschina.net/u/1778239/blog