参考博客:http://blog.csdn.net/xiangwanpeng/article/details/53907738

设想这样一种需求:要实现一个计算器,除了能够进行加减乘除运算之外,还有两个功能,一是日志功能,即能够记录程序的执行情况;二是验证功能,即对要计算的参数进行验证。 
  传统的实现方法是在每一个方法上都添加日志和验证功能

 

现在我们以上述问题为例,来简单测试Spring中的AOP功能。 
  首先新建对应的接口和类:

//计算器接口
public interface ArithmeticCalculator {

    int add(int i, int j);
    int sub(int i, int j);

    int mul(int i, int j);
    int div(int i, int j);

}

//计算器实现类
@Component("arithmeticCalculator")
public class ArithmeticCalculatorImpl implements ArithmeticCalculator {

    @Override
    public int add(int i, int j) {
        int result = i + j;
        return result;
    }

    @Override
    public int sub(int i, int j) {
        int result = i - j;
        return result;
    }

    @Override
    public int mul(int i, int j) {
        int result = i * j;
        return result;
    }

    @Override
    public int div(int i, int j) {
        int result = i / j;
        return result;
    }

}

 

  Spring中有两种方式用以实现AOP,一种是基于AspectJ注解的方式,另一种是基于XML配置文件的方式,下面逐一介绍。

基于AspectJ注解的方式

首先导入AspectJ的jar包: 

编写分别负责日志和验证功能的两个切面类:

//日志切面

//@Order指明切面的优先级,值越小优先级越高
@Order(2)
//通过添加 @Aspect 注解声明一个 bean 是一个切面
@Aspect
@Component
public class LoggingAcpect {

    /**
     * 定义一个方法, 用于声明切入点表达式. 一般地, 该方法中再不需要添入其他的代码. 
     * 使用 @Pointcut 来声明切入点表达式. 
     * 后面的其他通知直接使用方法名来引用当前的切入点表达式. 
     */
    @Pointcut("execution(* com.MySpring.aop.annotation.*.*(..))")
    public void declareJointPointExpression(){}

    /**
     * 前置通知:
     * 在 com.MySpring.aop.annotation 包下的每一个类的每一个方法开始之前执行一段代码
     */
    @Before("declareJointPointExpression()")
    public void beforeMethod(JoinPoint joinpoint){
        String methodName = joinpoint.getSignature().getName();
        Object[] args = joinpoint.getArgs();
        System.out.println("the method "+methodName+" begins with "+Arrays.asList(args));
    }

    /**
     * 后置通知:
     * 在 com.MySpring.aop.annotation 包下的每一个类的每一个方法开始后执行一段代码
     * 无论这段代码是否抛出异常
     */
    @After("declareJointPointExpression()")
    public void afterMethod(JoinPoint joinpoint){
        String methodName = joinpoint.getSignature().getName();
        Object[] args = joinpoint.getArgs();
        System.out.println("the method "+methodName+" ends");
    }


    /**
     * 返回通知:
     * 在方法法正常结束受执行的代码
     * 返回通知是可以访问到方法的返回值的!
     */
    @AfterReturning(value="declareJointPointExpression()",returning="result")
    public void afterReturning(JoinPoint joinpoint,Object result){
        String methodName = joinpoint.getSignature().getName();
        Object[] args = joinpoint.getArgs();
        System.out.println("the method "+methodName+" ends with result "+result);
    }

    /**
     * 异常通知:
     * 在目标方法出现异常时会执行的代码.
     * 可以访问到异常对象; 且可以指定在出现特定异常时在执行通知代码
     */
    @AfterThrowing(value="declareJointPointExpression()",throwing="e")
    public void afterThrowing(JoinPoint joinpoint,Exception e){
        String methodName = joinpoint.getSignature().getName();
        Object[] args = joinpoint.getArgs();
        System.out.println("the method "+methodName+" occurs exception "+e);
    }
}

//验证切面

@Order(1)
@Aspect
@Component
public class ValidationAspect {

    @Pointcut("execution(* com.MySpring.aop.annotation.*.*(..))")
    public void declareJointPointExpression(){}

    @Before("declareJointPointExpression()")
    public void validateArgs(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        System.out.println("-->validate args "+Arrays.asList(args));
    }

}
 

编写spring配置文件applicationContext-aop-annotation.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.MySpring.aop"></context:component-scan>

    <!-- 配置自动为匹配 aspectJ 注解的 Java 类生成代理对象 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>

 

编写测试类:

public class Test {

    @org.junit.Test
    public void test() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-aop-annotation.xml");
        ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
        System.out.println("result is "+arithmeticCalculator.add(100, 200));
        System.out.println("result is "+arithmeticCalculator.div(100, 0));
    }

}


基于XML配置文件的方式

首先新建接口和类,和上面类似,只是没有AspectJ的注解:

//日志切面
public class LoggingAcpect {


    public void beforeMethod(JoinPoint joinpoint){
        String methodName = joinpoint.getSignature().getName();
        Object[] args = joinpoint.getArgs();
        System.out.println("the method "+methodName+" begins with "+Arrays.asList(args));
    }

    public void afterMethod(JoinPoint joinpoint){
        String methodName = joinpoint.getSignature().getName();
        Object[] args = joinpoint.getArgs();
        System.out.println("the method "+methodName+" ends");
    }


    public void afterReturning(JoinPoint joinpoint,Object result){
        String methodName = joinpoint.getSignature().getName();
        Object[] args = joinpoint.getArgs();
        System.out.println("the method "+methodName+" ends with result "+result);
    }

    public void afterThrowing(JoinPoint joinpoint,Exception e){
        String methodName = joinpoint.getSignature().getName();
        Object[] args = joinpoint.getArgs();
        System.out.println("the method "+methodName+" occurs exception "+e);
    }

}

//验证切面
public class ValidationAspect {


    public void validateArgs(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        System.out.println("-->validate args "+Arrays.asList(args));
    }

}

 

编写spring配置文件applicationContext-aop-xml.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.MySpring.aop.xml"></context:component-scan>

    <!-- 配置切面的 bean. -->
    <bean id="loggingAspect" class="com.MySpring.aop.xml.LoggingAcpect"></bean>
    <bean id="validationAspect" class="com.MySpring.aop.xml.ValidationAspect"></bean>

    <!-- 配置 AOP -->
    <aop:config>

       <!-- 配置切点表达式 -->
        <aop:pointcut expression="execution(* com.MySpring.aop.xml.*.*(..))"
            id="pointcut" />

      <!-- 配置切面及通知 -->
        <aop:aspect ref="loggingAspect" order="2">
            <aop:before method="beforeMethod" pointcut-ref="pointcut" />
            <aop:after method="afterMethod" pointcut-ref="pointcut" />
            <aop:after-returning method="afterReturning"
                pointcut-ref="pointcut" returning="result" />
            <aop:after-throwing method="afterThrowing"
                pointcut-ref="pointcut" throwing="e" />
        </aop:aspect>

        <aop:aspect ref="validationAspect" order="1">
            <aop:before method="validateArgs" pointcut-ref="pointcut" />
        </aop:aspect>
    </aop:config>


</beans>

 

 

编写测试类:

public class Test {

    @org.junit.Test
    public void test() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-aop-xml.xml");
        ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
        System.out.println("result is "+arithmeticCalculator.add(100, 200));
        System.out.println("result is "+arithmeticCalculator.div(100, 0));
    }

}

 

运行结果: