SpringAOP 前置通知、后置通知

柔情只为你懂 2022-05-23 06:16 450阅读 0赞

AspectJ:Java社区中最完整、最流行的AOP框架。

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

在Spring中2启用AspectJ注解支持:

1、要在 Spring应用中使用AspectJ注解,需要添加spring-aspect、aspectj-weaver、aopalliance依赖

2、将aop Schema添加到根元素

3、要在SpringIOC容器中启用AspectJ注解支持,只要在Bean配置文件中定义一个空的XML元素:

4、在Spring IOC容器侦测到Bean配置文件中的元素时,会自动与AspectJ切面匹配的Bean创建代理。

一、基于注解的方式

1、依赖

2、在配置中加入aop的命名空间

3、基于注解的方式:

①在配置文件中加入:

配置文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. 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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  7. <!--配置自动扫描的包-->
  8. <context:component-scan base-package="aopImpl"/>
  9. <!--使AspectJ注解起作用:自动为匹配的类生成代理对象-->
  10. <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  11. </beans>

②把横切关注点的代码抽象到切面的类中

切面首先是一个IOC容器中的Bean,即加入@Component注解

切面还需要加入@AspectJ注解

③在类中声明各种通知:

1、声明一个方法

2、在方法前加入通知

@AspectJ支持的5中通知:

—@Before:前置通知在方法执行前执行

—@After:后置通知,在方法执行后执行

—@AfterReturning:返回通知,在方法返回结果之后执行

—@AfterThrowing:异常通知,在方法抛出异常后执行

—@Around:环绕通知,围绕着方法执行

④我们可以在通知方法中声明一个类型为JoinPoint参数,然后就能访问链接细节,如方法名称和参数值

切面类:

  1. package aopImpl;
  2. import org.aspectj.lang.JoinPoint;
  3. import org.aspectj.lang.annotation.Aspect;
  4. import org.aspectj.lang.annotation.Before;
  5. import org.springframework.stereotype.Component;
  6. import java.util.Arrays;
  7. import java.util.List;
  8. /** * 把这个类声明为一个切面: * 1、需要把该类放入到容器中(就是加上@Component注解) * 2、再声明为一个切面(加上@AspectJ注解) * * @author chenpeng * @date 2018/6/3 23:20 */ @Aspect
  9. @Component
  10. public class LoggingAspect {
  11. //声明该方法为一个前置通知:在目标方法开始之前执行
  12. //execution中是AspectJ表达式
  13. @Before(value = "execution(* aopImpl.ArithmeticCalculatorImpl.*(int ,int ))")
  14. public void beforeMethod(JoinPoint joinPoint){
  15. String methodName = joinPoint.getSignature().getName();
  16. List<Object> args = Arrays.asList(joinPoint.getArgs());
  17. System.out.println("beforeMethod "+methodName+" and "+args);
  18. }
  19. }

在使用的时候报错:因为动态代理不能用接口的实现类来转换Proxy的实现类,它们是同级,应该用共同的接口来转换。

70

改为这样:

  1. import aopImpl.ArithmeticCalculator;
  2. import aopImpl.ArithmeticCalculatorImpl;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. /** * @author chenpeng * @date 2018/6/3 23:16 */ public class aopImplTest {
  6. public static void main(String[] args) {
  7. //1、创建SpringIOC容器
  8. ApplicationContext context = new ClassPathXmlApplicationContext("aopImpl.xml");
  9. //2、从IOC容器中国获取Bean的实例
  10. ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) context.getBean("ArithmeticCalculatorImpl");
  11. //3、使用Bean
  12. int result = arithmeticCalculator.add(3,6);
  13. System.out.println(result);
  14. }
  15. }

其他通知:

  1. package aopImpl;
  2. import org.aspectj.lang.JoinPoint;
  3. import org.aspectj.lang.ProceedingJoinPoint;
  4. import org.aspectj.lang.annotation.*;
  5. import org.springframework.stereotype.Component;
  6. import java.util.Arrays;
  7. import java.util.List;
  8. /** * 把这个类声明为一个切面: * 1、需要把该类放入到容器中(就是加上@Component注解) * 2、再声明为一个切面(加上@AspectJ注解) * * @author chenpeng * @date 2018/6/3 23:20 */ @Aspect
  9. @Component
  10. public class LoggingAspect {
  11. //声明该方法为一个前置通知:在目标方法开始之前执行
  12. //execution中是AspectJ表达式
  13. @Before(value = "execution(* aopImpl.ArithmeticCalculatorImpl.*(int ,int ))")
  14. public void beforeMethod(JoinPoint joinPoint){
  15. String methodName = joinPoint.getSignature().getName();
  16. List<Object> args = Arrays.asList(joinPoint.getArgs());
  17. System.out.println("beforeMethod "+methodName+" start with "+args);
  18. }
  19. //后置通知,就是在目标方法执行之后(无论是否发生异常)执行的通知
  20. //后置通知中不能访问目标方法的返回结果
  21. @After(value = "execution(* aopImpl.ArithmeticCalculatorImpl.*(int ,int ))")
  22. public void afterMethod(JoinPoint joinPoint){
  23. String methodName = joinPoint.getSignature().getName();
  24. List<Object> args = Arrays.asList(joinPoint.getArgs());
  25. System.out.println("afterMethod "+methodName+" end with "+args);
  26. }
  27. //返回通知,在方法正常结束之后执行的代码
  28. //返回通知是可以访问到方法的返回值的
  29. @AfterReturning(value = "execution(* aopImpl.ArithmeticCalculatorImpl.*(int ,int ))",returning = "result")
  30. public void afterReturning(JoinPoint joinPoint,Object result){
  31. String methodName = joinPoint.getSignature().getName();
  32. List<Object> args = Arrays.asList(joinPoint.getArgs());
  33. System.out.println("afterReturning "+methodName+" end with "+result);
  34. }
  35. //返回异常通知,返回抛出异常的时候执行的通知,可以获得返回的异常
  36. //可以访问到异常对象,且可以指定在出现特定异常的时候再执行通知代码
  37. @AfterThrowing(value = "execution(* aopImpl.ArithmeticCalculatorImpl.*(int ,int ))",throwing = "ex")
  38. public void afterThrowing(JoinPoint joinPoint,Exception ex){
  39. String methodName = joinPoint.getSignature().getName();
  40. List<Object> args = Arrays.asList(joinPoint.getArgs());
  41. System.out.println("afterThrowing "+methodName+" end with "+ ex );
  42. }
  43. //环绕通知需要携带ProceedingJoinPoint类型的参数
  44. //环绕通知类似于动态代理的全过程,这个类型ProceedingJoinPoint的参数可以决定是否执行目标方法
  45. //且环绕通知必须有返回值,返回值即为目标方法返回值
  46. @Around(value = "execution(* aopImpl.ArithmeticCalculatorImpl.*(int ,int ))")
  47. public void around(ProceedingJoinPoint proceedingJoinPoint){
  48. Object result = null;
  49. String methodName = proceedingJoinPoint.getSignature().getName();
  50. Object[] args = proceedingJoinPoint.getArgs();
  51. //执行目标方法
  52. try {
  53. //前置通知
  54. System.out.println("beforeMethod "+methodName+" start with "+args);
  55. result = proceedingJoinPoint.proceed();
  56. //返回通知
  57. System.out.println("afterMethod "+methodName+" end with "+result);
  58. } catch (Throwable throwable) {
  59. //异常通知
  60. System.out.println("afterThrowing "+methodName+" exception with "+ throwable );
  61. throwable.printStackTrace();
  62. }
  63. //后置通知
  64. System.out.println("afterMethod "+methodName+" end with "+args);
  65. //System.out.println("around "+proceedingJoinPoint);
  66. return;
  67. }
  68. }

对于切面的优先级

可以在类上使用注解@Order(1),括号中的数字越小,优先级越高

  1. @Order(1)

重用切面的切点表达式:使用@Pointcut

70 1

  1. /** * 定义一个方法,用于声明切入点表达式 *一般的,该方法中不需要添加其他的代码 * 使用@Pointcut来声明切入点表达式 * 后面的其他通知直接使用方法名来引用切入点表达式 */ @Pointcut(value = "execution(* aopImpl.ArithmeticCalculatorImpl.*(int ,int ))")
  2. public void declareJoinPointExpress(){ }
  3. //声明该方法为一个前置通知:在目标方法开始之前执行
  4. //execution中是AspectJ表达式
  5. @Before(value = "declareJoinPointExpress()")
  6. public void beforeMethod(JoinPoint joinPoint){
  7. String methodName = joinPoint.getSignature().getName();
  8. List<Object> args = Arrays.asList(joinPoint.getArgs());
  9. System.out.println("beforeMethod "+methodName+" start with "+args);
  10. }

其他切面类中使用:

  1. package aopImpl;
  2. import org.aspectj.lang.JoinPoint;
  3. import org.aspectj.lang.annotation.Aspect;
  4. import org.aspectj.lang.annotation.Before;
  5. import org.springframework.core.annotation.Order;
  6. import org.springframework.stereotype.Component;
  7. import java.util.Arrays;
  8. /** * @author chenpeng * @date 2018/6/4 8:09 */ //可以使用@Order指定切面的优先级,值越小优先级越高
  9. @Order(1)
  10. @Component
  11. @Aspect
  12. public class ValidationAspect {
  13. @Before(value = "LoggingAspect.declareJoinPointExpress()")
  14. public void validateArgs(JoinPoint joinPoint){
  15. System.out.println("validateArgs"+ Arrays.asList(joinPoint.getArgs()));
  16. }
  17. }
二、基于XML配置文件的方式

除了使用@AspectJ注解声明切面,Spring还支持在Bean的配置文件中声明切面,这种声明是通过aop Schema中的XML元素完成的。

正常情况下,基于注解的声明要优于基于XML的声明,通过@AspectJ注解,可以与Aspect切面相兼容,而基于XML配置则是Spring专有的。由于@AspectJ得到越来越多AOP框架支持,所以用的更多。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
  8. <!--配置bean-->
  9. <bean id="arithmeticCalculatorImpl" class="XML.ArithmeticCalculatorImpl"/>
  10. <!--配置切面的bean-->
  11. <bean id="LoggingAspect" class="XML.LoggingAspect"/>
  12. <bean id="ValidationAspect" class="XML.ValidationAspect"/>
  13. <!--配置AOP-->
  14. <aop:config>
  15. <!--配置切点表达式-->
  16. <aop:pointcut id="pointcut" expression="execution(* XML.ArithmeticCalculatorImpl.*(..))"/>
  17. <!--配置切面及通知-->
  18. <aop:aspect ref="LoggingAspect" order="2">
  19. <aop:before method="beforeMethod" pointcut-ref="pointcut"/>
  20. <aop:after method="afterMethod" pointcut-ref="pointcut"/>
  21. <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="ex"/>
  22. <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
  23. </aop:aspect>
  24. <aop:aspect ref="ValidationAspect" order="1">
  25. <aop:before method="validateArgs" pointcut-ref="pointcut"/>
  26. </aop:aspect>
  27. </aop:config>
  28. </beans>

发表评论

表情:
评论列表 (有 0 条评论,450人围观)

还没有评论,来说两句吧...

相关阅读