Spring4-4 AOP配置

  在Java社区中,最完整且最流行的AOP框架是AspectJ;而在Spring2.0以上版本中,可以使用基于AspectJ注解的方式或基于XML文件的方式来配置AOP。


1. 基于AspectJ注解的方式配置AOP

1.1 实现步骤

  第一步:额外加入AspectJ所需要的jar包,具体如下图所示:
    这里写图片描述

  第二步:在Spring bean的配置文件中,进行如下操作:

  • 加入aop、bean和context的命名空间;
  • 配置自动扫描的包:如<context:component-scan base-package="com.qiaobc.spring.aop.impl"></context:component-scan>
  • 配置自动为匹配AspectJ注解的类生成代理对象:<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

.
  第三步:将横切关注点的代码抽象到切面类中,即需要为切面类添加@Component和@Aspect注解,并在类中声明通知。
  第四步:创建测试类并运行即可。

1.2 用AspectJ注解声明切面

  这里写图片描述

1.3 切入点表达式

  AspectJ的通知注解需要借助切入点表达式来匹配目标方法,具体说明如下:
  这里写图片描述

1.4 重用切入点

  这里写图片描述

1.5 附:核心测试代码

  基于AspectJ注解的方式配置AOP的示例代码下载地址:http://download.csdn.net/download/bingbeichen/9785907;其中,切面类的核心测试代码如下:

package com.qiaobc.spring.aop.impl;

import java.util.Arrays;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 切面类:需要放入IoC容器中(@Component)、再声明为一个切面(@Aspect)
 * 优先级:可以使用@Order(1)注解来指定切面的优先级,值越小优先级越高
 *      或 实现Ordered接口, getOrder()方法的返回值越小, 优先级越高
 * @author qiaobc
 */
@Aspect
@Component
public class LoggingAspect {

    /**
     * 声明切入点表达式:@Pointcut、该方法不需要填入其他代码
     * 引用切入点表达式:com.qiaobc.spring.aop.impl.LoggingAspect.declareJoinPointExpression()
     */
    @Pointcut("execution(public int com.qiaobc.spring.aop.impl.ArithmeticCalculator.*(..))")
    private void declareJoinPointExpression(){}

    /**
     * 需求:在com.qiaobc.spring.aop.impl.ArithmeticCalculator接口的所有实现类的每个方法执行前打印日志
     * 前置通知:在目标方法开始之前执行,用@Before来声明
     * @param joinPoint : 用于让通知访问当前连接点的具体细节
     */
    @Before(value = "declareJoinPointExpression()")
    public void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println("The method " + methodName + " begins with " + args);
    }

    /**
     * 后置通知:在目标方法执行之后执行(无论该方法是否出现异常),用@After来声明
     * 特别注意:在后置通知中无法访问目标方法的执行结果
     * @param joinPoint : 用于让通知访问当前连接点的具体细节
     */
    @After(value = "declareJoinPointExpression()")
    public void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " ends");
    }

    /**
     * 返回通知:在目标方法正常结束后执行的通知,其可以访问目标方法的返回值
     * @param joinPoint : 用于让通知访问当前连接点的具体细节
     * @param result : 用于获取目标方法的返回值
     */
    @AfterReturning(value = "declareJoinPointExpression()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method " + methodName + " ends with " + result);
    }

    /**
     * 异常通知:在目标方法抛出异常时执行的通知
     * @param joinPoint : 用于让通知访问当前连接点的具体细节
     * @param exception : 用于获取目标方法执行所抛出的异常(该参数类型可以设置只有发生指定异常时才执行)
     */
    @AfterThrowing(value = "declareJoinPointExpression()", throwing = "exception")
    public void afterThrowing(JoinPoint joinPoint, ArithmeticException exception) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Exception in method \"" + methodName + "\" " + exception);
    }

    /**
     * 环绕通知:类似于动态代理,其必须有返回值(目标方法的返回值)
     * @param proceedingJoinPoint : 环绕通知需要携带ProceedingJoinPoint类型的参数,用于决定是否执行目标方法
     */
    /*
    @Around (value = "execution(public int com.qiaobc.spring.aop.impl.ArithmeticCalculator.*(..))")
    public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint) {

        Object result = null;
        String methodName = proceedingJoinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(proceedingJoinPoint.getArgs());

        // 执行目标方法
        try {
            // 前置通知
            System.out.println("The method " + methodName + " begins with " + args);
            // 执行目标方法
            result = proceedingJoinPoint.proceed();
            // 返回通知
            System.out.println("The method " + methodName + " ends with " + result);
        } catch (Throwable e) {
            // 异常通知
            System.out.println("Exception in method \"" + methodName + "\" " + e);
            // 问题:org.springframework.aop.AopInvocationException: Null return value from advice does not match primitive return type ...
            throw new RuntimeException(e);
        }
        // 后置通知
        System.out.println("The method " + methodName + " ends");
        return result;
    }
    */

}

2. 基于XML文件的方式配置AOP

  基于XML文件的方式配置AOP的示例代码下载地址:http://download.csdn.net/download/bingbeichen/9785907;其中Spring bean配置文件的核心代码如下:

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 配置bean -->
    <bean id="arithmeticCalculator" class="com.qiaobc.spring.aop.impl.xml.ArithmeticCalculatorImpl"></bean>

    <!-- 配置切面bean -->
    <bean id="loggingAspect" class="com.qiaobc.spring.aop.impl.xml.LoggingAspect"></bean>

    <!-- 配置AOP -->
    <aop:config>
        <!-- 配置切入点表达式 -->
        <aop:pointcut expression="execution(* com.qiaobc.spring.aop.impl.xml.ArithmeticCalculator.*(..))" id="logging"/>
        <!-- 配置切面及通知 -->
        <aop:aspect ref="loggingAspect" order="1">
            <aop:before method="beforeMethod" pointcut-ref="logging"/>
            <aop:after method="afterMethod" pointcut-ref="logging"/>
            <aop:after-returning method="afterReturning" returning="result" pointcut-ref="logging"/>
            <aop:after-throwing method="afterThrowing" throwing="exception" pointcut-ref="logging"/>
        </aop:aspect>
    </aop:config>

</beans>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值