Spring AOP的理解与配置示例

引入问题:什么是AOP?

AOP(Aspect-Oriented Programming, 面向切面编程): 是一种新的方法论, 是对传统 OOP(Object-Oriented Programming, 面向对象编程) 的补充. AOP 的主要编程对象是切面(aspect), 而切面模块化横切关注点. 在应用 AOP 编程时, 仍然需要定义公共功能, 但可以明确的定义这个功能在哪里, 以什么方式应用,并且不必修改受影响的类. 这样一来横切关注点就被模块化到特殊的对象(切面)里.

AOP 的好处:

每个事物逻辑位于一个位置, 代码不分散, 便于维护和升级 业务模块更简洁, 只包含核心业务代码.

AOP 术语:

切面(Aspect) : 横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象
通知(Advice) : 切面必须要完成的工作
目标(Target) : 被通知的对象
代理(Proxy) : 向目标对象应用通知之后创建的对象
连接点(Joinpoint):程序执行的某个特定位置:如类某个方法调用前、调用后、方法抛出异常后等。连接点由两个信息确定:方法表示的程序执行点;相对点表示的方位。例如ArithmethicCalculator#add()方法执行前的连接点,执行点为ArithmethicCalculator#add();方位为该方法执行前的位置
切点(pointcut):每个类都拥有多个连接点:例如ArithmethicCalculator的所有方法实际上都是连接点,即连接点是程序类中客观存在的事务。AOP通过切点定位到特定的连接点。类比:连接点相当于数据库中的记录,切点相当于查询条件。切点和连接点不是一对一的关系,一个切点匹配多个连接点,切点通过org.springframework.aop.Pointcut接口进行描述,它使用类和方法作为连接点的查询条件。
这里写图片描述

配置篇:
在 Spring 中启用 AspectJ 注解支持:

•要在 Spring应用中使用AspectJ注解,必须在 classpath下包含AspectJ类库:aopalliance.jar、aspectj.weaver.jar和spring-aspects.jar
•要在 SpringIOC 容器中启用 AspectJ注解支持,只要在Bean配置文件中定义一个空的XML 元素<aop:aspectj-autoproxy/>
•当 SpringIOC 容器侦测到 Bean配置文件中的<aop:aspectj-autoproxy/>元素时,会自动为与AspectJ切面匹配的Bean创建代理.

基于注解的方式配置AOP:
用 AspectJ 注解声明切面:

•要在 Spring中声明AspectJ切面,只需要在IOC 容器中将切面声明为Bean实例.当在SpringIOC 容器中初始化
•在AspectJ注解中,切面只是一个带有@Aspect 注解的 Java类.
•通知是标注有某种注解的简单的 Java方法. •AspectJ
支持5种类型的通知注解:
–@Before: 前置通知,在方法执行之前执行 –@After: 后置通知,在方法执行之后执行
–@AfterRunning:返回通知,在方法返回结果之后执行
–@AfterThrowing:异常通知,在方法抛出异常之后
–@Around: 环绕通知,围绕着方法执行

代码:

import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 可以使用@Order注解指定切面的优先级,值越小优先级越高
 * @author cjb
 *
 */

@Order(2)
@Component
@Aspect
public class LoggingAspect {

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

    }
    /**
     * 在com.atguigu.spring.aop.ArithmeticCalculator 接口每一个实现类的每一个方法开始之前执行一段代码
     * 
     */
    @Before("declareJointPointExpression()")
    public void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        System.out.println("The method begins " + methodName + " begins with " + Arrays.asList(args));
    }

    /**
     * 在方法执行之后执行的代码,无论该方法是否出现异常
     * 
     * @param joinPoint
     */
    @After(("declareJointPointExpression()"))
    public void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();

        System.out.println("The method  " + methodName + " ends ");
    }

    /**
     * 在方法正常结束受执行的代码
     * 返回通知是可以访问到方法的返回值的!
     * @param joinPoint
     */
    @AfterReturning(value="declareJointPointExpression()",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 e
     */
    @AfterThrowing(throwing="e",value="execution(public int com.atguigu.spring.aop.ArithmeticCalculator.*(..))")
    public void afterThrowing(JoinPoint joinPoint,NullPointerException e) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method  " + methodName + " occure exception: " + e);
    }

    /**
     * 环绕通知需要携带 ProceedingJoinPoint类型的参数 
     * 环绕通知类似于动态代理的全过程:ProceedingJoinPoint 类型的参数可以决定是否执行目标方法
     * 且环绕通知必须有返回值,返回值即为目标方法的返回值
     * @param pjd
     */
    @Around("execution(public int com.atguigu.spring.aop.ArithmeticCalculator.*(..))")
    public Object aroundMethod(ProceedingJoinPoint pjd) {
        System.out.println("aroundMethod");

        Object result = null;
        String methodName = pjd.getSignature().getName();
        //执行目标方法
        try {
            //前置通知
            System.out.println("The method "+ methodName +" begins with" +Arrays.asList(pjd.getArgs()));
            result = pjd.proceed();
            //返回通知
            System.out.println("The method "+ methodName +" ends with" +result);
        } catch (Throwable e) {
            //异常通知
            System.out.println("The method occurs exception:" + e);
            throw new RuntimeException(e);
        }
        //后置通知
        System.out.println("The method "+methodName+" ends");
        return result;
    }

}

基于XML的方式配置AOP:

•当使用 XML 声明切面时,需要在根元素中导入aopSchema •在 Bean 配置文件中,所有的SpringAOP
配置都必须定义在 元素内部.对于每个切面而言,都要创建一个
元素来为具体的切面实现引用后端Bean实例. •切面 Bean 必须有一个标示符,供元素引用

声明切面和切入点的示例代码:

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

    <!-- 配置切面的bean. -->
    <bean id="loggingAspect" class="com.atguigu.spring.aop.xml.LoggingAspect"></bean>
    <bean id="vlidationAspect" class="com.atguigu.spring.aop.xml.VlidationAspect"></bean>

    <!-- 配置AOP -->
    <aop:config>
        <!-- 配置切点表达式 -->
        <aop:pointcut expression="execution(* com.atguigu.spring.aop.xml.ArithmeticCalculator.*(int ,int ))" id="pointcut"/>
        <!-- 配置切面及通知 -->
        <aop:aspect ref="loggingAspect" order="2">
        <!--
            <aop:before method="beforeMethod" pointcut-ref="pointcut"/>
            <aop:after method="afterMethod" pointcut-ref="pointcut"/>
            <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/>
            <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
          -->
          <aop:around method="aroundMethod" pointcut-ref="pointcut" />
        </aop:aspect>
        <aop:aspect ref="vlidationAspect" order="1">
            <aop:before method="vlidateArgs" pointcut-ref="pointcut"/>
        </aop:aspect>
    </aop:config>

代码:

import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class LoggingAspect {

    public void declareJointPointExpression() {

    }

    public void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        System.out.println("The method begins " + methodName + " begins with " + Arrays.asList(args));
    }

    public void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();

        System.out.println("The method  " + methodName + " ends ");
    }

    public void afterReturning(JoinPoint joinPoint,Object result) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method  " + methodName + " ends with " + result);
    }

    public void afterThrowing(JoinPoint joinPoint,NullPointerException e) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method  " + methodName + " occure exception: " + e);
    }

    public Object aroundMethod(ProceedingJoinPoint pjd) {
        System.out.println("aroundMethod");

        Object result = null;
        String methodName = pjd.getSignature().getName();
        //执行目标方法
        try {
            //前置通知
            System.out.println("The method "+ methodName +" begins with" +Arrays.asList(pjd.getArgs()));
            result = pjd.proceed();
            //返回通知
            System.out.println("The method "+ methodName +" ends with" +result);
        } catch (Throwable e) {
            //异常通知
            System.out.println("The method occurs exception:" + e);
            throw new RuntimeException(e);
        }
        //后置通知
        System.out.println("The method "+methodName+" ends");
        return result;
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值