AOP简介和测试

谁借莪1个温暖的怀抱¢ 2022-07-13 06:15 188阅读 0赞

AOP简介

  AOP,即面向切面编程,它是Spring中的两个重要内容之一。它是为了把逻辑代码和处理琐碎事务的代码分离开,以便能够分离复杂度。
  设想这样一种需求:要实现一个计算器,除了能够进行加减乘除运算之外,还有两个功能,一是日志功能,即能够记录程序的执行情况;二是验证功能,即对要计算的参数进行验证。
  传统的实现方法是在每一个方法上都添加日志和验证功能,例如,对于日志功能,实现代码如下:
  image\_1b51si3u71l4318p4avfpsk1de9.png-96.3kB
  这将导致的问题有:
  1. 代码混乱:越来越多的非业务需求(日志和验证等)加入后,原有的业务方法急剧膨胀,每个方法在处理核心逻辑的同时还必须兼顾其他多个关注点。
  2. 代码分散: 以日志需求为例,只是为了满足这个单一需求,就不得不在多个模块(方法)里多次重复相同的日志代码,如果日志需求发生变化,必须修改所有模块。
  这正是AOP可以解决的问题,AOP的主要编程对象是切面(Aspect),切面可以模块化横切关注点,例如,上述例子中的日志和验证功能都可以被模块化到特定的切面类中。AOP解决上述问题的原理如下图所示:

image\_1b51sr8es1fofg7tjq5hfk8okm.png-62.3kB

  AOP中的相关术语如下:
  
image\_1b51tbooa11me1b8k1utd1q30197b1g.png-102.9kB
    
  现在我们以上述问题为例,来简单测试Spring中的AOP功能。
  首先新建对应的接口和类:

  1. //计算器接口
  2. public interface ArithmeticCalculator {
  3. int add(int i, int j);
  4. int sub(int i, int j);
  5. int mul(int i, int j);
  6. int div(int i, int j);
  7. }
  8. //计算器实现类
  9. @Component("arithmeticCalculator")
  10. public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
  11. @Override
  12. public int add(int i, int j) {
  13. int result = i + j;
  14. return result;
  15. }
  16. @Override
  17. public int sub(int i, int j) {
  18. int result = i - j;
  19. return result;
  20. }
  21. @Override
  22. public int mul(int i, int j) {
  23. int result = i * j;
  24. return result;
  25. }
  26. @Override
  27. public int div(int i, int j) {
  28. int result = i / j;
  29. return result;
  30. }
  31. }

  Spring中有两种方式用以实现AOP,一种是基于AspectJ注解的方式,另一种是基于XML配置文件的方式,下面逐一介绍。

基于AspectJ注解的方式

首先导入AspectJ的jar包:
image\_1b51t6f1c1tpfqb5sekh451rjm13.png-9kB

编写分别负责日志和验证功能的两个切面类:

  1. //日志切面
  2. //@Order指明切面的优先级,值越小优先级越高
  3. @Order(2)
  4. //通过添加 @Aspect 注解声明一个 bean 是一个切面
  5. @Aspect
  6. @Component
  7. public class LoggingAcpect {
  8. /** * 定义一个方法, 用于声明切入点表达式. 一般地, 该方法中再不需要添入其他的代码. * 使用 @Pointcut 来声明切入点表达式. * 后面的其他通知直接使用方法名来引用当前的切入点表达式. */
  9. @Pointcut("execution(* com.MySpring.aop.annotation.*.*(..))")
  10. public void declareJointPointExpression(){}
  11. /** * 前置通知: * 在 com.MySpring.aop.annotation 包下的每一个类的每一个方法开始之前执行一段代码 */
  12. @Before("declareJointPointExpression()")
  13. public void beforeMethod(JoinPoint joinpoint){
  14. String methodName = joinpoint.getSignature().getName();
  15. Object[] args = joinpoint.getArgs();
  16. System.out.println("the method "+methodName+" begins with "+Arrays.asList(args));
  17. }
  18. /** * 后置通知: * 在 com.MySpring.aop.annotation 包下的每一个类的每一个方法开始后执行一段代码 * 无论这段代码是否抛出异常 */
  19. @After("declareJointPointExpression()")
  20. public void afterMethod(JoinPoint joinpoint){
  21. String methodName = joinpoint.getSignature().getName();
  22. Object[] args = joinpoint.getArgs();
  23. System.out.println("the method "+methodName+" ends");
  24. }
  25. /** * 返回通知: * 在方法法正常结束受执行的代码 * 返回通知是可以访问到方法的返回值的! */
  26. @AfterReturning(value="declareJointPointExpression()",returning="result")
  27. public void afterReturning(JoinPoint joinpoint,Object result){
  28. String methodName = joinpoint.getSignature().getName();
  29. Object[] args = joinpoint.getArgs();
  30. System.out.println("the method "+methodName+" ends with result "+result);
  31. }
  32. /** * 异常通知: * 在目标方法出现异常时会执行的代码. * 可以访问到异常对象; 且可以指定在出现特定异常时在执行通知代码 */
  33. @AfterThrowing(value="declareJointPointExpression()",throwing="e")
  34. public void afterThrowing(JoinPoint joinpoint,Exception e){
  35. String methodName = joinpoint.getSignature().getName();
  36. Object[] args = joinpoint.getArgs();
  37. System.out.println("the method "+methodName+" occurs exception "+e);
  38. }
  39. }
  40. //验证切面
  41. @Order(1)
  42. @Aspect
  43. @Component
  44. public class ValidationAspect {
  45. @Pointcut("execution(* com.MySpring.aop.annotation.*.*(..))")
  46. public void declareJointPointExpression(){}
  47. @Before("declareJointPointExpression()")
  48. public void validateArgs(JoinPoint joinPoint){
  49. Object[] args = joinPoint.getArgs();
  50. System.out.println("-->validate args "+Arrays.asList(args));
  51. }
  52. }

编写spring配置文件applicationContext-aop-annotation.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
  3. <!-- 配置自动扫描的包 -->
  4. <context:component-scan base-package="com.MySpring.aop"></context:component-scan>
  5. <!-- 配置自动为匹配 aspectJ 注解的 Java 类生成代理对象 -->
  6. <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  7. </beans>

编写测试类:

  1. public class Test {
  2. @org.junit.Test
  3. public void test() {
  4. ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-aop-annotation.xml");
  5. ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
  6. System.out.println("result is "+arithmeticCalculator.add(100, 200));
  7. System.out.println("result is "+arithmeticCalculator.div(100, 0));
  8. }
  9. }
  10. 运行结果:
  11. ![image_1b51tt9lh1cl9f228c3i6u34s1t.png-26.2kB][5]

基于XML配置文件的方式

首先新建接口和类,和上面类似,只是没有AspectJ的注解:

  1. //日志切面
  2. public class LoggingAcpect {
  3. public void beforeMethod(JoinPoint joinpoint){
  4. String methodName = joinpoint.getSignature().getName();
  5. Object[] args = joinpoint.getArgs();
  6. System.out.println("the method "+methodName+" begins with "+Arrays.asList(args));
  7. }
  8. public void afterMethod(JoinPoint joinpoint){
  9. String methodName = joinpoint.getSignature().getName();
  10. Object[] args = joinpoint.getArgs();
  11. System.out.println("the method "+methodName+" ends");
  12. }
  13. public void afterReturning(JoinPoint joinpoint,Object result){
  14. String methodName = joinpoint.getSignature().getName();
  15. Object[] args = joinpoint.getArgs();
  16. System.out.println("the method "+methodName+" ends with result "+result);
  17. }
  18. public void afterThrowing(JoinPoint joinpoint,Exception e){
  19. String methodName = joinpoint.getSignature().getName();
  20. Object[] args = joinpoint.getArgs();
  21. System.out.println("the method "+methodName+" occurs exception "+e);
  22. }
  23. }
  24. //验证切面
  25. public class ValidationAspect {
  26. public void validateArgs(JoinPoint joinPoint){
  27. Object[] args = joinPoint.getArgs();
  28. System.out.println("-->validate args "+Arrays.asList(args));
  29. }
  30. }

编写spring配置文件applicationContext-aop-xml.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
  3. <!-- 配置自动扫描的包 -->
  4. <context:component-scan base-package="com.MySpring.aop.xml"></context:component-scan>
  5. <!-- 配置切面的 bean. -->
  6. <bean id="loggingAspect" class="com.MySpring.aop.xml.LoggingAcpect"></bean>
  7. <bean id="validationAspect" class="com.MySpring.aop.xml.ValidationAspect"></bean>
  8. <!-- 配置 AOP -->
  9. <aop:config>
  10.    <!-- 配置切点表达式 -->
  11. <aop:pointcut expression="execution(* com.MySpring.aop.xml.*.*(..))" id="pointcut" />
  12.       <!-- 配置切面及通知 -->
  13. <aop:aspect ref="loggingAspect" order="2">
  14. <aop:before method="beforeMethod" pointcut-ref="pointcut" />
  15. <aop:after method="afterMethod" pointcut-ref="pointcut" />
  16. <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result" />
  17. <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e" />
  18. </aop:aspect>
  19. <aop:aspect ref="validationAspect" order="1">
  20. <aop:before method="validateArgs" pointcut-ref="pointcut" />
  21. </aop:aspect>
  22. </aop:config>
  23. </beans>

编写测试类:

  1. public class Test {
  2. @org.junit.Test
  3. public void test() {
  4. ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-aop-xml.xml");
  5. ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
  6. System.out.println("result is "+arithmeticCalculator.add(100, 200));
  7. System.out.println("result is "+arithmeticCalculator.div(100, 0));
  8. }
  9. }

运行结果:
image\_1b51v0fmeqn91ev715b1tpbfhg2a.png-23.4kB

发表评论

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

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

相关阅读

    相关 AOP 简介

    AOP 术语 1、切面(Aspect): 横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象 2、通知(Advice): 切面必须要完成的工作 3、目标(Ta

    相关 AOP面向切面编程简介

           AOP这个词相信大家都没有接触太多过,但是实际上你们已经有所接触了,就在设计模式中。AOP所用的思想其实和设计模式是一样的,即在不修改原代码的情况下统一增加或者修