Spring知识整理(六)Spring之AOP的前置通知,后置通知,返回通知,异常通知,环绕通知

1.(AspectJ

 

AspectJJava 社区里最完整最流行的 AOP 框架.

Spring2.0以上版本, 可以使用基于 AspectJ注解或基于 XML 配置的 AOP

要在 Spring 应用中使用 AspectJ注解, 必须在 classpath下包含 AspectJ类库: aopalliance.jaraspectj.weaver.jar spring-aspects.jar

aop Schema 添加到 <beans> 根元素中.

Spring IOC 容器中启用 AspectJ注解支持, 只要Bean 配置文件中定义一个空的 XML 元素 <aop:aspectj-autoproxy>

SpringIOC 容器侦测到 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: 环绕通知, 围绕着方法执行

1.1(前置通知)

 

前置通知:在方法执行之前执行的通知

前置通知使用 @Before 注解, 并将切入点表达式的值作为注解值.

可以在通知方法中声明一个类型为 JoinPoint的参数. 然后就能访问链接细节.

1.2(后置通知)

 

后置通知是在连接点完成之后执行的, 即连接点返回结果或者抛出异常的时候, 下面的后置通知记录了方法的终止.

一个切面可以包括一个或者多个通知.使用@After注解

1.3(返回通知)

 

无论连接点是正常返回还是抛出异常, 后置通知都会执行. 如果只想在连接点返回的时候做记录, 应使用返回通知代替后置通知.

在返回通知中, 只要将 returning属性添加到 @AfterReturning注解中, 就可以访问连接点的返回值. 该属性的值即为用来传入返回值的参数名称.

必须在通知方法的签名中添加一个同名参数. 在运行时, Spring AOP 会通过这个参数传递返回值.

 

1.4(异常通知)

 

只在连接点抛出异常时才执行异常通知

throwing 属性添加到 @AfterThrowing注解中, 也可以访问连接点抛出的异常. Throwable是所有错误和异常类的超类. 所以在异常通知方法可以捕获到任何错误和异常.

如果只对某种特殊的异常类型感兴趣, 可以将参数声明为其他异常的参数类型. 然后通知就只在抛出这个类型及其子类的异常时才被执行.

 

1.5(环绕通知(类似于动态代理))

 

环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点.

对于环绕通知来说, 连接点的参数类型必须是 ProceedingJoinPoint . 它是 JoinPoint的子接口, 允许控制何时执行, 是否执行连接点.

在环绕通知中需要明确调用 ProceedingJoinPointproceed() 方法来执行被代理的方法. 如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行.

注意: 环绕通知的方法需要返回目标方法执行之后的结果, 即调用 joinPoint.proceed(); 的返回值, 否则会出现空指针异常

 

2.(代码说明)

 

2.1(目标方法所在的bean)

 

package com.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);
   
}
 
package com.spring.aop;

import org.springframework.stereotype.Component;

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

}

 

2.2(切面)

 

package com.spring.aop;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * AOP 的配置顺序
 * 1. 加入 jar 包
 * com.springsource.net.sf.cglib-2.2.0.jar
 * com.springsource.org.aopalliance-1.0.0.jar
 * com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
 * spring-aspects-4.0.0.RELEASE.jar
 *
 * 2. 在 Spring 的配置文件中加入 aop 的命名空间。
 *
 * 3. 基于注解的方式来使用 AOP
 * 3.1 在配置文件中配置自动扫描的包: <context:component-scan base-package="com.spring.aop"></context:component-scan>
 * 3.2 加入使 AspjectJ 注解起作用的配置: <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
 * 为匹配的类自动生成动态代理对象.
 *
 * 4. 编写切面类:
 * 4.1 一个一般的 Java 类
 * 4.2 在其中添加要额外实现的功能.
 *
 * 5. 配置切面
 * 5.1 切面必须是 IOC 中的 bean: 实际添加了 @Component 注解
 * 5.2 声明是一个切面: 添加 @Aspect
 * 5.3 声明通知: 即额外加入功能对应的方法.
 * 5.3.1 前置通知: @Before("execution(public int com.spring.aop.ArithmeticCalculator.*(int, int))")
 * @Before 表示在目标方法执行之前执行 @Before 标记的方法的方法体.
 * @Before 里面的是切入点表达式:
 *
 * 6. 在通知中访问连接细节: 可以在通知方法中添加 JoinPoint 类型的参数, 从中可以访问到方法的签名和方法的参数.
 *
 * 7. @After 表示后置通知: 在方法执行之后执行的代码.
 */

//通过添加 @Aspect 注解声明一个 bean 是一个切面!
//需要把该类放入到IOC容器中,再声明为一个切面
@Aspect
@Component
public class LoggingAspect {

   @Before("execution(public int com.spring.aop.ArithmeticCalculator.*(int, int))")
   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("execution(* com.spring.aop.*.*(..))")
   public void afterMethod(JoinPoint joinPoint){
      String methodName = joinPoint.getSignature().getName();
      System.out.println("The method " + methodName + " ends");
   }
   /**
    * 定义一个方法, 用于声明切入点表达式. 一般地, 该方法中再不需要添入其他的代码.
    * 使用 @Pointcut 来声明切入点表达式.
    * 后面的其他通知直接使用方法名来引用当前的切入点表达式.
    */
   @Pointcut("execution(public int com.spring.aop.ArithmeticCalculator.*(..))")
   public void declareJointPointExpression(){}
   /**
    * 在方法法正常结束受执行的代码
    * 返回通知是可以访问到方法的返回值的!
    */
   @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);
   }

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

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

      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 " + methodName + " occurs exception:" + e);
         throw new RuntimeException(e);
      }
      //后置通知
      System.out.println("The method " + methodName + " ends");

      return result;
   }
   */

}

2.3(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>

2.4(Main)

 

package com.spring.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
   
   public static void main(String[] args) {
      ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-aop.xml");
      ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
      System.out.println(arithmeticCalculator.getClass().getName());
      int result = arithmeticCalculator.add(11, 12);
      System.out.println("result:" + result);
      result = arithmeticCalculator.div(21, 3);
      System.out.println("result:" + result);

   }
   
}

2.5(运行结果)

                     

2.6(总结)

通过上面的步骤以及运行结果我们可发现,运行的过程有点像动态代理,Spring的IOC在生成切面的时候会根据切点找到对应的bean,然后为其生成代理对象

3.(切面的优先级)

 

在同一个连接点上应用不止一个切面时, 除非明确指定, 否则它们的优先级是不确定的.

切面的优先级可以通过实现 Ordered 接口或利用 @Order 注解指定.

若使用 @Order 注解, 序号出现在注解中

                              

                               

4.(重用切入点定义)

 

在编写 AspectJ切面时, 可以直接在通知注解中书写切入点表达式. 但同一个切点表达式可能会在多个通知中重复出现.

AspectJ切面中, 可以通过 @Pointcut注解将一个切入点声明成简单的方法. 切入点的方法体通常是空的, 因为将切入点定义与应用程序逻辑混在一起是不合理的.

切入点方法的访问控制符同时也控制着这个切入点的可见性. 如果切入点要在多个切面中共用, 最好将它们集中在一个公共的类中. 在这种情况下, 它们必须被声明为 public. 在引入这个切入点时, 必须将类名也包括在内. 如果类没有与这个切面放在同一个包中, 还必须包含包名.

其他通知可以通过方法名称引入该切入点.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值