Spring(二)——AOP

一、AOP术语

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

二、AOP的实现——AspectJ

AOP可以通过AspectJ注解进行配置,也可以通过XML配置。这里推荐使用AspectJ注解,下面的实例也都是通过AspectJ举例,XML配置将被放在最后进行简单说明。

关于AspectJ:

AspectJ是Java 社区里最完整最流行的 AOP 框架。

在Spring中启动 AspectJ支持:

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

三、声明切面、通知

要在 Spring 中声明 AspectJ 切面, 只需要在 IOC 容器中将切面声明为 Bean 实例.
当在 Spring IOC 容器中初始化 AspectJ 切面之后, Spring IOC 容器就会为那些与 AspectJ 切面相匹配的 Bean 创建代理.
在 AspectJ 注解中, 切面只是一个带有 ==@Aspect== 注解的 Java 类.

通知是标注有某种注解的简单的 Java 方法.
AspectJ 支持 5 种类型的通知注解:
@Before: 前置通知, 在方法执行之前执行
@After: 后置通知, 在方法执行之后执行
@AfterRunning: 返回通知, 在方法返回结果之后执行
@AfterThrowing: 异常通知, 在方法抛出异常之后
@Around: 环绕通知, 围绕着方法执行

一个切面可以包括一个或者多个通知

举例:

切入表达式:
如上面的方法中@Before(“execution(* ArithmeticCalculator.add(..))”)
最典型的切入点表达式时根据方法的签名来匹配各种方法, 例如:
execution * com.atguigu.spring.ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 中声明的所有方法,第一个 * 代表任意修饰符及任意返回值. 第二个 * 代表任意方法. .. 匹配任意数量的参数. 若目标类与接口与该切面在同一个包中, 可以省略包名.
execution public * ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 接口的所有公有方法.
execution public double ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 中返回 double 类型数值的方法
execution public double ArithmeticCalculator.*(double, ..): 匹配第一个参数为 double 类型的方法, .. 匹配任意数量任意类型的参数
execution public double ArithmeticCalculator.*(double, double): 匹配参数类型为 double, double 类型的方法.

合并切入表达式:
在 AspectJ 中, 切入点表达式可以通过操作符 &&, ||, ! 结合起来.
enter description here

让通知访问当前连接点的细节:
可以在通知方法中声明一个类型为 JoinPoint 的参数. 然后就能访问链接细节. 如方法名称和参数值
enter description here

常用方法:
JointPoint.getSignatrue.getName():获得方法名
JoinPoint.getArgs():获得参数值

前置通知

前置通知:在方法执行之前执行的通知
前置通知使用 @Before 注解, 并将切入点表达式的值作为注解值.

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

后置通知

后置通知是在连接点完成之后执行的, 即连接点返回结果或者抛出异常的时候, 下面的后置通知记录了方法的终止.
无论连接点是正常返回还是抛出异常, 后置通知都会执行.
如果只想在连接点返回的时候记录日志, 应使用 返回通知 代替后置通知.

    @After("declareJointPointExpression()")
    public void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method "+methodName+" ends");
    }

返回通知

在返回通知中, 只要将 ==returning 属性==添加到 ==@AfterReturning== 注解中, 就可以访问连接点的返回值. 该属性的值即为用来传入返回值的参数名称.
必须在通知方法的签名中添加一个同名参数. 在运行时, Spring AOP 会通过这个参数传递返回值.
原始的切点表达式需要出现在 pointcut 属性中

/**
     * 返回通知
     * 在方法正常结束后执行的代码,可以访问到方法的返回值!
     * @param joinPoint
     * @param result :方法返回值
     */
    @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);
    }

异常通知

只在连接点抛出异常时才执行异常通知
将 ==throwing 属性==添加到 ==@AfterThrowing== 注解中, 也可以访问连接点抛出的异常.
Throwable 是所有错误和异常类的超类. 所以在异常通知方法可以捕获到任何错误和异常.
如果只对某种特殊的异常类型感兴趣, 可以将参数声明为其他异常的参数类型. 然后通知就只在抛出这个类型及其子类的异常时才被执行.

     /**
     * 异常通知
     * 在目标方法发生异常时会执行的方法,可以访问到异常对象,且可以指定在出现特定异常时再执行(写在参数里)
     * @param joinPoint
     * @param ex
     */
    @AfterThrowing(value="declareJointPointExpression()",throwing="ex")
    public void afterThrowing(JoinPoint joinPoint,Exception ex) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method "+methodName+" occurs exception :"+ex);
    }

环绕通知

环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点.
对于环绕通知来说, 连接点的参数类型必须是 ==ProceedingJoinPoint== . 它是 JoinPoint 的子接口, 允许控制何时执行, 是否执行连接点.
在环绕通知中需要明确调用 ==ProceedingJoinPoint 的 proceed() 方法==来执行被代理的方法. 如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行.
注意: 环绕通知的方法需要返回目标方法执行之后的结果, 即调用 joinPoint.proceed(); 的返回值, 否则会出现空指针异常

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

        Object result = null;
        String methodName = pjd.getSignature().getName();

        //执行目标方法
        try {
            //前置通知
            System.out.println("(around)The mehod "+ methodName + " begins with "+pjd.getArgs());

            result = pjd.proceed();

            //后置通知
            System.out.println("(around)The mehod "+ methodName + " ends with"+ result);
        } catch (Throwable e) {
            //异常通知
            System.out.println("(around)The method occurs exception with"+ e);
            throw new RuntimeException();
        }

        //后置通知
        System.out.println("(around)The method ends~");
        return result;
    }

整合后的代码:

ArithmeticCalculator是一个超类,通过一个子类ArithmeticCalculatorImpl实现

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

LoggingAspect是一个切面,也是一个Java类,通过这个类实现通知

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(2) //这里是为切面设置优先级,当有多个切面的时候,将起作用。数字越小优先级越高
@Component //这里将切面声明为 Bean 实例. 通过注解加入IoC容器
@Aspect//声明一个切面
public class LoggingAspect {

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

    }
    /**
     * 前置通知
     * 在ArithmeticCalculator接口的每一个实现类的每一个方法开始之前执行一段代码
     * @param joinPoint
     */
    @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));
    }

    /**
     * 后置通知
     * 在ArithmeticCalculator接口的每一个实现类的每一个方法执行之后执行的方法,无论方法是否发生异常
     * @param joinPoint
     */
    @After("declareJointPointExpression()")
    public void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method "+methodName+" ends");
    }

    /**
     * 返回通知
     * 在方法正常结束后执行的代码,可以访问到方法的返回值!
     * @param joinPoint
     * @param result :方法返回值
     */
    @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 ex
     */
    @AfterThrowing(value="declareJointPointExpression()",throwing="ex")
    public void afterThrowing(JoinPoint joinPoint,Exception ex) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println("The method "+methodName+" occurs exception :"+ex);
    }

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


        Object result = null;
        String methodName = pjd.getSignature().getName();

        //执行目标方法
        try {
            //前置通知
            System.out.println("(around)The mehod "+ methodName + " begins with "+pjd.getArgs());

            result = pjd.proceed();

            //后置通知
            System.out.println("(around)The mehod "+ methodName + " ends with"+ result);
        } catch (Throwable e) {
            //异常通知
            System.out.println("(around)The method occurs exception with"+ e);
            throw new RuntimeException();
        }

        //后置通知
        System.out.println("(around)The method ends~");
        return result;
    }*/
}

VlidationAspect是第二个Aspect切面,通过order指定优先级


//Order注解指定切面的优先级:数字越小优先级越高
@Order(1)
@Component
@Aspect
public class VlidationAspect {

    @Before("LoggingAspect.declareJointPointExpression()")
    public void validateArgs(JoinPoint joinPoint) {
        System.out.println("->validate: "+Arrays.asList(joinPoint.getArgs()));
    }
}

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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

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

    <!-- 使 AspectJ 的注解起作用 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>

下面是主类

public class Main {

    public static void main(String[] args) {
        ApplicationContext ctx  = new ClassPathXmlApplicationContext("applicationContext.xml");
        ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");

        System.out.println(arithmeticCalculator.getClass().getName());
        int result = arithmeticCalculator.add(1, 2);
        System.out.println("(main)result:" + result);

        result = arithmeticCalculator.div(200, 10);
        System.out.println("(main)result:"+result);
    }
}

执行结果:

com.sun.proxy.$Proxy12
->validate: [1, 2]
The method add begins with [1, 2]
The method add ends
The method add ends with 3
(main)result:3
->validate: [200, 10]
The method div begins with [200, 10]
The method div ends
The method div ends with 20
(main)result:20

猜你喜欢

转载自blog.csdn.net/github_38687585/article/details/79920258