AOP简介和测试

AOP简介

  AOP,即面向切面编程,它是Spring中的两个重要内容之一。它是为了把逻辑代码和处理琐碎事务的代码分离开,以便能够分离复杂度。
  设想这样一种需求:要实现一个计算器,除了能够进行加减乘除运算之外,还有两个功能,一是日志功能,即能够记录程序的执行情况;二是验证功能,即对要计算的参数进行验证。
  传统的实现方法是在每一个方法上都添加日志和验证功能,例如,对于日志功能,实现代码如下:
  image_1b51si3u71l4318p4avfpsk1de9.png-96.3kB
  这将导致的问题有:
  1. 代码混乱:越来越多的非业务需求(日志和验证等)加入后,原有的业务方法急剧膨胀,每个方法在处理核心逻辑的同时还必须兼顾其他多个关注点。
  2. 代码分散: 以日志需求为例,只是为了满足这个单一需求,就不得不在多个模块(方法)里多次重复相同的日志代码,如果日志需求发生变化,必须修改所有模块。
  这正是AOP可以解决的问题,AOP的主要编程对象是切面(Aspect),切面可以模块化横切关注点,例如,上述例子中的日志和验证功能都可以被模块化到特定的切面类中。AOP解决上述问题的原理如下图所示:

image_1b51sr8es1fofg7tjq5hfk8okm.png-62.3kB

  AOP中的相关术语如下:
  
image_1b51tbooa11me1b8k1utd1q30197b1g.png-102.9kB
    
  现在我们以上述问题为例,来简单测试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包:
image_1b51t6f1c1tpfqb5sekh451rjm13.png-9kB

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

//日志切面

//@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));
    }

}
运行结果:

![image_1b51tt9lh1cl9f228c3i6u34s1t.png-26.2kB][5]

基于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));
    }

}

运行结果:
image_1b51v0fmeqn91ev715b1tpbfhg2a.png-23.4kB

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值