Spring Aop

来源:互联网 发布:微扬网络 大写青春 编辑:程序博客网 时间:2024/06/03 21:05

0、AOP实现原理

面向方面编程(Aspect Oriented Programming,简称AOP)是一种声明式编程(Declarative Programming)。AOP的实现原理可以看作是Proxy/Decorator设计模式的泛化,如下为Proxy模式的简单例子

Java代码  收藏代码
  1. Proxy {   
  2.     innerObject; // 真正的对象   
  3.     f1() {   
  4.         // 做一些额外的事情  
  5.         innerObject.f1(); // 调用真正的对象的对应方法  
  6.         // 做一些额外的事情   
  7.     }   
  8. }   
1、使用代理实现AOP

声明一个服务类接口IService.java

Java代码  收藏代码
  1. package com.chenzehe.aop;  
  2. public interface IService {  
  3.     int save();  
  4. }  
 实现类:
Java代码  收藏代码
  1. package com.chenzehe.aop;  
  2. public class Service implements IService {  
  3.     final Logger    log = LoggerFactory.getLogger(Service.class);  
  4.       
  5.     @Override  
  6.     public int save() {  
  7.         log.info("*****save*****");  
  8.         return 0;  
  9.     }     
  10. }  

再声明一个代理类ServiceProxy也实现IService接口,内部调用Service的实现方法,并在前面和后台添加自己的切面方法:

Java代码  收藏代码
  1. package com.chenzehe.aop;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. public class ServiceProxy implements IService {  
  6.     final Logger    log = LoggerFactory.getLogger(ServiceProxy.class);  
  7.     private IService    service;      
  8.     public ServiceProxy(IService service) {  
  9.         this.service = service;  
  10.     }  
  11.       
  12.     @Override  
  13.     public int save() {  
  14.         int result;  
  15.         log.debug("*****Before*****");  
  16.         result = service.save();  
  17.         log.debug("*****After*****");  
  18.         return result;  
  19.     }     
  20. }  

添加单元测试类ProxyTest使用ServiceProxy

Java代码  收藏代码
  1. import org.junit.Test;  
  2. public class ProxyTest {  
  3.     @Test  
  4.     public void testSave() {  
  5.         IService service = new ServiceProxy(new Service());  
  6.         service.save();  
  7.     }  
  8. }  
  9. 方法输出:  
  10. ServiceProxy - *****Before*****  
  11.        *****save*****  
  12. ServiceProxy - *****After*****  

 2、使用动态代理实现AOP

上面代码实现了最简单的AOP功能,但是如果项目中有很多像Service这样的类,那就需要写很多ServiceProxy这样的代理类来实现,所以需要动态代码方法来实现,也就是实现InvocationHandler的接口, 这个类可以让我们在JVM调用某个类的方法时动态的为些方法做些什么事,如下代码,IService接口和实现类Service不变,添加动态代理实现类DynamicProxy:

 

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import java.lang.reflect.InvocationHandler;  
  9. import java.lang.reflect.Method;  
  10. import java.lang.reflect.Proxy;  
  11.   
  12. import org.slf4j.Logger;  
  13. import org.slf4j.LoggerFactory;  
  14.   
  15. public class DynamicProxy implements InvocationHandler {  
  16.     final Logger    log = LoggerFactory.getLogger(ServiceProxy.class);  
  17.     /** 
  18.      * 要处理的对象(也就是我们要在方法的前后加上业务逻辑的对象) 
  19.      */  
  20.     private Object  delegate;  
  21.       
  22.     /** 
  23.      * 动态生成方法被处理过后的对象 (写法固定) 
  24.      */  
  25.     public Object bind(Object delegate) {  
  26.         this.delegate = delegate;  
  27.         return Proxy.newProxyInstance(this.delegate.getClass().getClassLoader(), this.delegate.getClass().getInterfaces(), this);  
  28.     }  
  29.       
  30.     @Override  
  31.     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  
  32.         Object result;  
  33.         log.debug("*****Before*****");  
  34.         result = method.invoke(this.delegate, args);  
  35.         log.debug("*****After*****");  
  36.         return result;  
  37.     }  
  38.       
  39. }  

 单元测试代码如下:

 

Java代码  收藏代码
  1. package com.chenzehe.aop;  
  2.   
  3. import org.junit.Test;  
  4.   
  5. public class DynamicProxyTest {  
  6.     @Test  
  7.     public void testSave() {  
  8.         IService service = (IService) new DynamicProxy().bind(new Service());  
  9.         service.save();  
  10.     }  
  11. }  
  12.   
  13. 输出:  
  14. ServiceProxy - *****Before*****  
  15.        *****save*****  
  16. ServiceProxy - *****After*****  

 

 3、通知解耦

上面代码虽然实现了切面通知,但是通知方法都是在代理方法中实现,这样耦合度太高,我们可以抽象出一个接口,这个接口里就只有两个方法,一个是在被代理对象要执行方法之前执行的方法,我们取名为before,第二个方法就是在被代理对象执行方法之后执行的方法,我们取名为after,接口定义如下 :

Java代码  收藏代码
  1. package com.chenzehe.aop;  
  2.   
  3. import java.lang.reflect.Method;  
  4.   
  5. public interface IOperation {  
  6.     /** 
  7.      * 方法执行之前的操作 
  8.      *  
  9.      * @param method 
  10.      */  
  11.     void before(Method method);  
  12.       
  13.     /** 
  14.      * 方法执行之后的操作 
  15.      *  
  16.      * @param method 
  17.      */  
  18.     void after(Method method);  
  19. }  

 我们去写一个实现上面接口的类.我们把作他真正的操作者,如下面是日志操作者的一个类:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import java.lang.reflect.Method;  
  9.   
  10. import org.slf4j.Logger;  
  11. import org.slf4j.LoggerFactory;  
  12.   
  13. public class LoggerOperation implements IOperation {  
  14.     final Logger    log = LoggerFactory.getLogger(LoggerOperation.class);  
  15.       
  16.     @Override  
  17.     public void before(Method method) {  
  18.         log.info("Before:" + method.getName());  
  19.     }  
  20.       
  21.     @Override  
  22.     public void after(Method method) {  
  23.         log.info("After:" + method.getName());  
  24.     }  
  25.       
  26. }  

 动态代理实现类:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import java.lang.reflect.InvocationHandler;  
  9. import java.lang.reflect.Method;  
  10. import java.lang.reflect.Proxy;  
  11.   
  12. public class OperationDynamicProxy implements InvocationHandler {  
  13.     /** 
  14.      * 要处理的对象(也就是我们要在方法的前后加上业务逻辑的对象) 
  15.      */  
  16.     private Object  delegate;  
  17.     /** 
  18.      * 切面操作方法 
  19.      */  
  20.     private Object  operation;  
  21.       
  22.     public OperationDynamicProxy() {  
  23.     }  
  24.       
  25.     /** 
  26.      * 动态生成方法被处理过后的对象 (写法固定) 
  27.      */  
  28.     public Object bind(Object delegate, Object operation) {  
  29.         this.delegate = delegate;  
  30.         this.operation = operation;  
  31.           
  32.         return Proxy.newProxyInstance(this.delegate.getClass().getClassLoader(), this.delegate.getClass().getInterfaces(), this);  
  33.     }  
  34.       
  35.     @Override  
  36.     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {  
  37.         Object result;  
  38.         // 反射得到操作者的实例  
  39.         Class clazz = this.operation.getClass();  
  40.         // 反射得到操作者的before方法  
  41.         Method start = clazz.getDeclaredMethod("before"new Class[] { Method.class });  
  42.         // 反射执行before方法  
  43.         start.invoke(this.operation, new Object[] { method });  
  44.         // 执行要处理对象的原本方法  
  45.         result = method.invoke(this.delegate, args);  
  46.         // 反射得到操作者的end方法  
  47.         Method end = clazz.getDeclaredMethod("after"new Class[] { Method.class });  
  48.         // 反射执行end方法  
  49.         end.invoke(this.operation, new Object[] { method });  
  50.         return result;  
  51.     }  
  52.       
  53. }  

 测试类:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import org.junit.Test;  
  9.   
  10. public class OperationDynamicProxyTest {  
  11.     @Test  
  12.     public void testSave() {  
  13.         IService service = (IService) new OperationDynamicProxy().bind(new Service(), new LoggerOperation());  
  14.         service.save();  
  15.     }  
  16. }  
  17.   
  18. 输出:  
  19. LoggerOperation - Before:save  
  20.        *****save*****  
  21. LoggerOperation - After:save  

 

4、使用CGLib实现

上面实现AOP中被代理对象都是提供接口的,有时候我们的需求中被代理类并不提供接口,此时使用CGLib来实现,CGLib实现原理是继承被代理类,重写被代理类的的方法,然后在重写方法中添加自己的切面方法。

没有实现提供的类:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. public class ServiceNotInterface {  
  9.     final Logger    log = LoggerFactory.getLogger(ServiceNotInterface.class);  
  10.       
  11.     public int save() {  
  12.         log.info("*****save*****");  
  13.         return 0;  
  14.     }     
  15. }  

 CGLib实现类:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import java.lang.reflect.Method;  
  9.   
  10. import net.sf.cglib.proxy.Enhancer;  
  11. import net.sf.cglib.proxy.MethodInterceptor;  
  12. import net.sf.cglib.proxy.MethodProxy;  
  13.   
  14. public class CGLibProxy implements MethodInterceptor {  
  15.     /** 
  16.      * 要处理的对象 
  17.      */  
  18.     private Object  delegate;  
  19.     /** 
  20.      * 切面操作方法 
  21.      */  
  22.     private Object  operation;  
  23.       
  24.     /** 
  25.      * 动态生成方法被处理过后的对象 
  26.      */  
  27.     public Object bind(Object delegate, Object operation) {  
  28.         this.delegate = delegate;  
  29.         this.operation = operation;  
  30.         Enhancer enhancer = new Enhancer();  
  31.         enhancer.setSuperclass(this.delegate.getClass());  
  32.         // 回调方法  
  33.         enhancer.setCallback(this);  
  34.         // 创建代理对象  
  35.         return enhancer.create();  
  36.           
  37.     }  
  38.       
  39.     @Override  
  40.     public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {  
  41.         Object result;  
  42.         // 反射得到操作者的实例  
  43.         Class clazz = this.operation.getClass();  
  44.         // 反射得到操作者的before方法  
  45.         Method start = clazz.getDeclaredMethod("before"new Class[] { Method.class });  
  46.         // 反射执行before方法  
  47.         start.invoke(this.operation, new Object[] { method });  
  48.         // 执行要处理对象的原本方法  
  49.         result = methodProxy.invokeSuper(proxy, args);  
  50.         // 反射得到操作者的end方法  
  51.         Method end = clazz.getDeclaredMethod("after"new Class[] { Method.class });  
  52.         // 反射执行end方法  
  53.         end.invoke(this.operation, new Object[] { method });  
  54.         return result;  
  55.     }  
  56.       
  57. }  

 测试类:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import java.lang.reflect.Method;  
  9.   
  10. import org.junit.Test;  
  11.   
  12. import net.sf.cglib.proxy.Enhancer;  
  13. import net.sf.cglib.proxy.MethodInterceptor;  
  14. import net.sf.cglib.proxy.MethodProxy;  
  15.   
  16. public class CGLibProxyTest {  
  17.     @Test  
  18.     public void testSave() {  
  19.         ServiceNotInterface service = (ServiceNotInterface) new CGLibProxy().bind(new ServiceNotInterface(), new LoggerOperation());  
  20.         service.save();  
  21.     }  
  22. }  
  23.   
  24. 输出:  
  25. LoggerOperation - Before:save  
  26.        *****save*****  
  27. LoggerOperation - After:save  

 

 5、Spring AOP概念

       切面(aspect):用来切插业务方法的类。
  连接点(joinpoint):是切面类和业务类的连接点,其实就是封装了业务方法的一些基本属性,作为通知的参数来解析。
  通知(advice):在切面类中,声明对业务方法做额外处理的方法。
  切入点(pointcut):业务类中指定的方法,作为切面切入的点。其实就是指定某个方法作为切面切的地方。
  目标对象(target object):被代理对象。
  AOP代理(aop proxy):代理对象。
  前置通知(before advice):在切入点之前执行。
  后置通知(after returning advice):在切入点执行完成后,执行通知。
  环绕通知(around advice):包围切入点,调用方法前后完成自定义行为。
  异常通知(after throwing advice):在切入点抛出异常后,执行通知。

       Spring提供了三种实现AOP的方式,Spring接口方式、schema配置方式和注解方式的三种实现方式。

6、接口方式

利用Spring AOP接口实现AOP,主要是为了指定自定义通知来供spring AOP机制识别。主要接口:前置通知 MethodBeforeAdvice ,后置通知:AfterReturningAdvice,环绕通知:MethodInterceptor,异常通知:ThrowsAdvice 。如下代码:

使用上面的接口IService和实现类Service

前置通知:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import java.lang.reflect.Method;  
  9.   
  10. import org.slf4j.Logger;  
  11. import org.slf4j.LoggerFactory;  
  12. import org.springframework.aop.MethodBeforeAdvice;  
  13.   
  14. /** 
  15.  * 前置通知 
  16.  */  
  17.   
  18. public class BaseBeforeAdvice implements MethodBeforeAdvice {  
  19.       
  20.     final Logger    log = LoggerFactory.getLogger(BaseBeforeAdvice.class);  
  21.       
  22.     /** 
  23.      * method : 切入的方法 <br> 
  24.      * args :切入方法的参数 <br> 
  25.      * target :目标对象 
  26.      */  
  27.     @Override  
  28.     public void before(Method method, Object[] args, Object target) throws Throwable {  
  29.         log.info("===========进入beforeAdvice()============ \n");  
  30.         log.info("准备在" + target + "对象上用");  
  31.         log.info(method + "方法");  
  32.         log.info("要进入切入点方法了 \n");  
  33.     }  
  34.       
  35. }  

 后置通知:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import java.lang.reflect.Method;  
  9.   
  10. import org.slf4j.Logger;  
  11. import org.slf4j.LoggerFactory;  
  12. import org.springframework.aop.AfterReturningAdvice;  
  13.   
  14. /** 
  15.  * 后置通知 
  16.  */  
  17. public class BaseAfterReturnAdvice implements AfterReturningAdvice {  
  18.       
  19.     final Logger    log = LoggerFactory.getLogger(BaseAfterReturnAdvice.class);  
  20.       
  21.     /** 
  22.      * returnValue :切入点执行完方法的返回值,但不能修改 <br> 
  23.      * method :切入点方法 <br> 
  24.      * args :切入点方法的参数数组 <br> 
  25.      * target :目标对象 
  26.      */  
  27.     @Override  
  28.     public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {  
  29.         log.info("==========进入afterReturning()=========== \n");  
  30.     }  
  31.       
  32. }  

 环绕通知:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import java.lang.reflect.Method;  
  9.   
  10. import org.aopalliance.intercept.MethodInterceptor;  
  11. import org.aopalliance.intercept.MethodInvocation;  
  12. import org.slf4j.Logger;  
  13. import org.slf4j.LoggerFactory;  
  14.   
  15. /** 
  16.  * 环绕通知 
  17.  */  
  18.   
  19. public class BaseAroundAdvice implements MethodInterceptor {  
  20.     final Logger    log = LoggerFactory.getLogger(BaseAroundAdvice.class);  
  21.       
  22.     /** 
  23.      * invocation :连接点 
  24.      */  
  25.     @Override  
  26.     public Object invoke(MethodInvocation invocation) throws Throwable {  
  27.         log.info("===========进入around环绕方法!=========== \n");  
  28.         // 调用目标方法之前执行的动作  
  29.         log.info("调用方法之前: 执行!\n");  
  30.         // 调用方法的参数  
  31.         Object[] args = invocation.getArguments();  
  32.         // 调用的方法  
  33.         Method method = invocation.getMethod();  
  34.         // 获取目标对象  
  35.         Object target = invocation.getThis();  
  36.         // 执行完方法的返回值:调用proceed()方法,就会触发切入点方法执行  
  37.         Object returnValue = invocation.proceed();  
  38.         log.info("===========结束进入around环绕方法!=========== \n");  
  39.         log.info("输出:" + args + ";" + method + ";" + target + ";" + returnValue + "\n");  
  40.         log.info("调用方法结束:之后执行!\n");  
  41.         return returnValue;  
  42.     }  
  43.       
  44. }  

 异常通知:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import java.lang.reflect.Method;  
  9.   
  10. import org.slf4j.Logger;  
  11. import org.slf4j.LoggerFactory;  
  12. import org.springframework.aop.ThrowsAdvice;  
  13.   
  14. /** 
  15.  * 异常通知,接口没有包含任何方法。通知方法自定义 
  16.  */  
  17. public class BaseAfterThrowsAdvice implements ThrowsAdvice {  
  18.     final Logger    log = LoggerFactory.getLogger(BaseAfterThrowsAdvice.class);  
  19.       
  20.     /** 
  21.      * 通知方法,需要按照这种格式书写 
  22.      *  
  23.      * @param method 
  24.      *            可选:切入的方法 
  25.      * @param args 
  26.      *            可选:切入的方法的参数 
  27.      * @param target 
  28.      *            可选:目标对象 
  29.      * @param throwable 
  30.      *            必填 : 异常子类,出现这个异常类的子类,则会进入这个通知。 
  31.      */  
  32.     public void afterThrowing(Method method, Object[] args, Object target, Throwable throwable) {  
  33.         log.info("出错啦");  
  34.     }  
  35. }  

 定义指定切点:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import java.lang.reflect.Method;  
  9.   
  10. import org.springframework.aop.support.NameMatchMethodPointcut;  
  11.   
  12. /** 
  13.  * 定义一个切点,指定对应方法匹配。来供切面来针对方法进行处理<br> 
  14.  * 继承NameMatchMethodPointcut类,来用方法名匹配 
  15.  */  
  16. public class Pointcut extends NameMatchMethodPointcut {  
  17.       
  18.     private static final long   serialVersionUID    = 5891054717975242200L;  
  19.       
  20.     @SuppressWarnings("rawtypes")  
  21.     @Override  
  22.     public boolean matches(Method method, Class targetClass) {  
  23.         // 设置单个方法匹配  
  24.         this.setMappedName("delete");  
  25.         // 设置多个方法匹配  
  26.         String[] methods = { "delete""save" };  
  27.           
  28.         // 也可以用“ * ” 来做匹配符号  
  29.         // this.setMappedName("get*");  
  30.           
  31.         this.setMappedNames(methods);  
  32.           
  33.         return super.matches(method, targetClass);  
  34.     }  
  35. }  

 配置:

Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop"  
  6.     xsi:schemaLocation="       
  7.           http://www.springframework.org/schema/beans       
  8.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd       
  9.           http://www.springframework.org/schema/context       
  10.           http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  11.           http://www.springframework.org/schema/aop       
  12.           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"  
  13.     default-autowire="byName">  
  14.   
  15.     <!-- ==============================利用spring自己的aop配置================================ -->  
  16.     <!-- 声明一个业务类 -->  
  17.     <bean id="service" class="com.chenzehe.aop.Service" />  
  18.   
  19.     <!-- 声明通知类 -->  
  20.     <bean id="baseBefore" class="com.chenzehe.aop.BaseBeforeAdvice" />  
  21.     <bean id="baseAfterReturn" class="com.chenzehe.aop.BaseAfterReturnAdvice" />  
  22.     <bean id="baseAfterThrows" class="com.chenzehe.aop.BaseAfterThrowsAdvice" />  
  23.     <bean id="baseAround" class="com.chenzehe.aop.BaseAroundAdvice" />  
  24.   
  25.     <!-- 指定切点匹配类 -->  
  26.     <bean id="pointcut" class="com.chenzehe.aop.Pointcut" />  
  27.   
  28.     <!-- 包装通知,指定切点 -->  
  29.     <bean id="matchBeforeAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">  
  30.         <property name="pointcut">  
  31.             <ref bean="pointcut" />  
  32.         </property>  
  33.         <property name="advice">  
  34.             <ref bean="baseBefore" />  
  35.         </property>  
  36.     </bean>  
  37.   
  38.     <!-- 使用ProxyFactoryBean 产生代理对象 -->  
  39.     <bean id="businessProxy" class="org.springframework.aop.framework.ProxyFactoryBean">  
  40.         <!-- 代理对象所实现的接口 ,如果有接口可以这样设置 -->  
  41.         <property name="proxyInterfaces">  
  42.             <value>com.chenzehe.aop.IService</value>  
  43.         </property>  
  44.   
  45.         <!-- 设置目标对象 -->  
  46.         <property name="target">  
  47.             <ref local="service" />  
  48.         </property>  
  49.         <!-- 代理对象所使用的拦截器 -->  
  50.         <property name="interceptorNames">  
  51.             <list>  
  52.                 <value>matchBeforeAdvisor</value>  
  53.                 <value>baseAfterReturn</value>  
  54.                 <value>baseAround</value>  
  55.             </list>  
  56.         </property>  
  57.     </bean>  
  58. </beans>  

 测试类:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import org.junit.Test;  
  9. import org.springframework.context.ApplicationContext;  
  10. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  11.   
  12. public class SpringAopInterfaceTest {  
  13.       
  14.     @Test  
  15.     public void testSpringAopInterface() {  
  16.         ApplicationContext context = new ClassPathXmlApplicationContext("spring-aop.xml");  
  17.         IService service = (IService) context.getBean("businessProxy");  
  18.         service.save();  
  19.     }  
  20. }  

 输出:

Java代码  收藏代码
  1. BaseBeforeAdvice - ===========进入beforeAdvice()============   
  2.   
  3. BaseBeforeAdvice - 准备在com.chenzehe.aop.Service@1e136a8对象上用  
  4. BaseBeforeAdvice - public abstract int com.chenzehe.aop.IService.save()方法  
  5. BaseBeforeAdvice - 要进入切入点方法了   
  6.   
  7. BaseAroundAdvice - ===========进入around环绕方法!===========   
  8.   
  9. BaseAroundAdvice - 调用方法之前: 执行!  
  10.   
  11. Service - *****save*****  
  12. BaseAroundAdvice - ===========结束进入around环绕方法!===========   
  13.   
  14. BaseAroundAdvice - 输出:[Ljava.lang.Object;@ee558f;public abstract int com.chenzehe.aop.IService.save();com.chenzehe.aop.Service@1e136a8;0  
  15.   
  16. BaseAroundAdvice - 调用方法结束:之后执行!  
  17.   
  18. BaseAfterReturnAdvice - ==========进入afterReturning()===========   

       前置方法会在切入点方法之前执行,后置会在切入点方法执行之后执行,环绕则会在切入点方法执行前执行同事方法结束也会执行对应的部分。主要是调用proceed()方法来执行切入点方法。配置 businessProxy这个bean的时候,ProxyFactoryBean类中指定了,proxyInterfaces参数。这里把他配置了IService接口。因为在项目开发过程中,往往业务类都会有对应的接口,以方便利用IOC解耦。但Spring AOP却也能支持没有接口的代理。这就是为什么需要导入cglib.jar的包了。在目标切入对象如果有实现接口,spring会默认走jdk动态代理来实现代理类。如果没有接口,则会通过cglib来实现代理类。

 

 7、使用aspectj来配置AOP

使用上面没有实现接口的业务类ServiceNotInterface

定义切面类AspectAdvice,包含了所有的通知:

Java代码  收藏代码
  1. package com.chenzehe.aop;  
  2.   
  3. import org.aspectj.lang.JoinPoint;  
  4. import org.aspectj.lang.ProceedingJoinPoint;  
  5. import org.slf4j.Logger;  
  6. import org.slf4j.LoggerFactory;  
  7.   
  8. /** 
  9.  * 定义一个切面 
  10.  *  
  11.  */  
  12. public class AspectAdvice {  
  13.     final Logger    log = LoggerFactory.getLogger(AspectAdvice.class);  
  14.       
  15.     /** 
  16.      * 前置通知 
  17.      *  
  18.      * @param jp 
  19.      *            连接点 
  20.      */  
  21.     public void doBefore(JoinPoint jp) {  
  22.         log.info("===========进入before advice============ \n");  
  23.         log.info("要进入切入点方法了 \n");  
  24.     }  
  25.       
  26.     /** 
  27.      * 后置通知 
  28.      *  
  29.      * @param jp 
  30.      *            连接点 
  31.      * @param result 
  32.      *            返回值 
  33.      */  
  34.     public void doAfter(JoinPoint jp, String result) {  
  35.         log.info("==========进入after advice=========== \n");  
  36.     }  
  37.       
  38.     /** 
  39.      * 环绕通知 
  40.      *  
  41.      * @param pjp 
  42.      *            连接点 
  43.      */  
  44.     public void doAround(ProceedingJoinPoint pjp) throws Throwable {  
  45.         log.info("===========进入around环绕方法!=========== \n");  
  46.           
  47.         // 调用目标方法之前执行的动作  
  48.         log.info("调用方法之前: 执行!\n");  
  49.           
  50.         // 调用方法的参数  
  51.         Object[] args = pjp.getArgs();  
  52.         // 调用的方法名  
  53.         String method = pjp.getSignature().getName();  
  54.         // 获取目标对象  
  55.         Object target = pjp.getTarget();  
  56.         // 执行完方法的返回值:调用proceed()方法,就会触发切入点方法执行  
  57.         Object result = pjp.proceed();  
  58.           
  59.         log.info("输出:" + args + ";" + method + ";" + target + ";" + result + "\n");  
  60.         log.info("调用方法结束:之后执行!\n");  
  61.     }  
  62.       
  63.     /** 
  64.      * 异常通知 
  65.      *  
  66.      * @param jp 
  67.      * @param e 
  68.      */  
  69.     public void doThrow(JoinPoint jp, Throwable e) {  
  70.         log.info("删除出错啦");  
  71.     }  
  72.       
  73. }  

 配置文件:

Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop"  
  6.     xsi:schemaLocation="       
  7.           http://www.springframework.org/schema/beans       
  8.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd       
  9.           http://www.springframework.org/schema/context       
  10.           http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  11.           http://www.springframework.org/schema/aop       
  12.           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"  
  13.     default-autowire="byName">  
  14.   
  15.     <!-- ==============================利用spring 利用aspectj来配置AOP================================ -->  
  16.   
  17.     <!-- 声明一个业务类 -->  
  18.     <bean id="aspectBusiness" class="com.chenzehe.aop.ServiceNotInterface" />  
  19.   
  20.     <!-- 声明通知类 -->  
  21.     <bean id="aspectAdvice" class="com.chenzehe.aop.AspectAdvice" />  
  22.   
  23.     <aop:config>  
  24.         <aop:aspect id="businessAspect" ref="aspectAdvice">  
  25.             <!-- 配置指定切入的对象 -->  
  26.             <aop:pointcut id="point_cut" expression="execution(* com.chenzehe.aop.ServiceNotInterface.*(..))" />  
  27.   
  28.             <!-- 前置通知 -->  
  29.             <aop:before method="doBefore" pointcut-ref="point_cut" />  
  30.             <!-- 后置通知 returning指定返回参数 -->  
  31.             <aop:after-returning method="doAfter"  
  32.                 pointcut-ref="point_cut" returning="result" />  
  33.             <aop:around method="doAround" pointcut-ref="point_cut" />  
  34.             <aop:after-throwing method="doThrow" pointcut-ref="point_cut"  
  35.                 throwing="e" />  
  36.         </aop:aspect>  
  37.     </aop:config>  
  38. </beans>  

 测试类:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import org.junit.Test;  
  9. import org.springframework.context.ApplicationContext;  
  10. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  11.   
  12. public class SpringAopAspectjTest {  
  13.     @Test  
  14.     public void testSpringAopAspectj() {  
  15.         ApplicationContext context = new ClassPathXmlApplicationContext("spring-aspectj-aop.xml");  
  16.         ServiceNotInterface service = (ServiceNotInterface) context.getBean("aspectBusiness");  
  17.         service.save();  
  18.     }  
  19. }  

 输出:

Java代码  收藏代码
  1. AspectAdvice - ===========进入before advice============   
  2.   
  3. AspectAdvice - 要进入切入点方法了   
  4.   
  5. DefaultListableBeanFactory - Returning cached instance of singleton bean 'aspectAdvice'  
  6. AspectAdvice - ===========进入around环绕方法!===========   
  7.   
  8. AspectAdvice - 调用方法之前: 执行!  
  9.   
  10. ServiceNotInterface - *****save*****  
  11. AspectAdvice - 输出:[Ljava.lang.Object;@edf389;save;com.chenzehe.aop.ServiceNotInterface@59fb21;0  
  12.   
  13. AspectAdvice - 调用方法结束:之后执行!  

 

 8、使用aspectj注解来配置AOP

基于注解的service类:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import org.slf4j.Logger;  
  9. import org.slf4j.LoggerFactory;  
  10. import org.springframework.stereotype.Component;  
  11.   
  12. /** 
  13.  * @description 
  14.  *  
  15.  * @author chenzehe 
  16.  * @email hljuczh@163.com 
  17.  */  
  18. @Component  
  19. public class ServiceAnonotation {  
  20.     final Logger    log = LoggerFactory.getLogger(ServiceAnonotation.class);  
  21.       
  22.     public int save() {  
  23.         log.info("*****save*****");  
  24.         return 0;  
  25.     }  
  26.       
  27. }  

 基于注解的切面:

Java代码  收藏代码
  1. package com.chenzehe.aop;  
  2.   
  3. import org.aspectj.lang.JoinPoint;  
  4. import org.aspectj.lang.ProceedingJoinPoint;  
  5. import org.aspectj.lang.annotation.AfterReturning;  
  6. import org.aspectj.lang.annotation.AfterThrowing;  
  7. import org.aspectj.lang.annotation.Around;  
  8. import org.aspectj.lang.annotation.Aspect;  
  9. import org.aspectj.lang.annotation.Before;  
  10. import org.aspectj.lang.annotation.Pointcut;  
  11. import org.slf4j.Logger;  
  12. import org.slf4j.LoggerFactory;  
  13. import org.springframework.stereotype.Component;  
  14.   
  15. /** 
  16.  * 定义一个切面 
  17.  *  
  18.  */  
  19. @Component  
  20. @Aspect  
  21. public class AspectAdviceAnonotation {  
  22.     final Logger    log = LoggerFactory.getLogger(AspectAdviceAnonotation.class);  
  23.       
  24.     /** 
  25.      * 指定切入点匹配表达式,注意它是以方法的形式进行声明的。 
  26.      */  
  27.     @Pointcut("execution(* com.chenzehe.aop.*.*(..))")  
  28.     public void anyMethod() {  
  29.     }  
  30.       
  31.     /** 
  32.      * 前置通知 
  33.      *  
  34.      * @param jp 
  35.      */  
  36.     @Before(value = "execution(* com.chenzehe.aop.*.*(..))")  
  37.     public void doBefore(JoinPoint jp) {  
  38.         log.info("===========进入before advice============ \n");  
  39.         log.info("要进入切入点方法了 \n");  
  40.     }  
  41.       
  42.     /** 
  43.      * 后置通知 
  44.      *  
  45.      * @param jp 
  46.      *            连接点 
  47.      * @param result 
  48.      *            返回值 
  49.      */  
  50.     @AfterReturning(value = "anyMethod()", returning = "result")  
  51.     public void doAfter(JoinPoint jp, String result) {  
  52.         log.info("==========进入after advice=========== \n");  
  53.     }  
  54.       
  55.     /** 
  56.      * 环绕通知 
  57.      *  
  58.      * @param pjp 
  59.      *            连接点 
  60.      */  
  61.     @Around(value = "execution(* com.chenzehe.aop.*.*(..))")  
  62.     public void doAround(ProceedingJoinPoint pjp) throws Throwable {  
  63.         log.info("===========进入around环绕方法!=========== \n");  
  64.           
  65.         // 调用目标方法之前执行的动作  
  66.         log.info("调用方法之前: 执行!\n");  
  67.           
  68.         // 调用方法的参数  
  69.         Object[] args = pjp.getArgs();  
  70.         // 调用的方法名  
  71.         String method = pjp.getSignature().getName();  
  72.         // 获取目标对象  
  73.         Object target = pjp.getTarget();  
  74.         // 执行完方法的返回值:调用proceed()方法,就会触发切入点方法执行  
  75.         Object result = pjp.proceed();  
  76.           
  77.         log.info("输出:" + args + ";" + method + ";" + target + ";" + result + "\n");  
  78.         log.info("调用方法结束:之后执行!\n");  
  79.     }  
  80.       
  81.     /** 
  82.      * 异常通知 
  83.      *  
  84.      * @param jp 
  85.      * @param e 
  86.      */  
  87.     @AfterThrowing(value = "execution(* com.chenzehe.aop.*.*(..))", throwing = "e")  
  88.     public void doThrow(JoinPoint jp, Throwable e) {  
  89.         log.info("删除出错啦");  
  90.     }  
  91.       
  92. }  

 配置文件:

Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop"  
  6.     xsi:schemaLocation="       
  7.           http://www.springframework.org/schema/beans       
  8.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd       
  9.           http://www.springframework.org/schema/context       
  10.           http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  11.           http://www.springframework.org/schema/aop       
  12.           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"  
  13.     default-autowire="byName">  
  14.   
  15.     <context:component-scan base-package="com.chenzehe.aop" />  
  16.     <!-- 打开aop 注解 -->  
  17.     <aop:aspectj-autoproxy />  
  18.   
  19. </beans>  

 测试类:

Java代码  收藏代码
  1. /** 
  2.  * Huisou.com Inc. 
  3.  * Copyright (c) 2011-2012 All Rights Reserved. 
  4.  */  
  5.   
  6. package com.chenzehe.aop;  
  7.   
  8. import org.junit.Test;  
  9. import org.springframework.context.ApplicationContext;  
  10. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  11.   
  12. /** 
  13.  * @description 
  14.  *  
  15.  * @author chenzehe 
  16.  * @email hljuczh@163.com 
  17.  */  
  18.   
  19. public class SpringAopAspectjAnonotationTest {  
  20.     @Test  
  21.     public void testSpringAopAspectjAnonotation() {  
  22.         ApplicationContext context = new ClassPathXmlApplicationContext("spring-aspectj-anonotation-aop.xml");  
  23.         ServiceAnonotation service = (ServiceAnonotation) context.getBean("serviceAnonotation");  
  24.         service.save();  
  25.     }  
  26. }  

 输出:

Java代码  收藏代码
  1. AspectAdviceAnonotation - ===========进入before advice============   
  2.   
  3. AspectAdviceAnonotation - 要进入切入点方法了   
  4.   
  5. AspectAdviceAnonotation - ===========进入around环绕方法!===========   
  6.   
  7. AspectAdviceAnonotation - 调用方法之前: 执行!  
  8.   
  9. ServiceAnonotation - *****save*****  
  10. AspectAdviceAnonotation - 输出:[Ljava.lang.Object;@7ecd78;save;com.chenzehe.aop.ServiceAnonotation@16be68f;0  
  11.   
  12. AspectAdviceAnonotation - 调用方法结束:之后执行!  
原创粉丝点击