Spring(4、AOP) 不念不忘少年蓝@ 2022-06-14 05:19 159阅读 0赞 **注:本文用到的jar请到**[Spring(1-1、基于xml装配Bean)][Spring_1-1_xml_Bean]**中查找** AOP(Aspect-OrientedProgramming,**面向切面编程**): 是一种新的方法论, 是对传统 OOP(Object-Oriented Programming, 面向对象编程) 的补充. AOP 的主要编程对象是**切面**(aspect), 而**切面模块化横切关注点**. 在应用 AOP 编程时, 仍然需要**定义公共功能**, 但可以明确的定义这个功能在哪里, 以什么方式应用, 并且**不必修改受影响的类**. 这样一来**横切关注点就被模块化到特殊的对象(切面)**里. AOP的好处: 每个事物逻辑位于一个位置, 代码不分散, 便于维护和升级 业务模块更简洁, 只包含核心业务代码. ### 专业术语 ### 切面(Aspect): **横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象** 通知(Advice): **切面必须要完成的工作** 目标(Target): **被通知的对象** 代理(Proxy): **向目标对象应用通知之后创建的对象** 连接点(Joinpoint):**程序执行的某个特定位置**:如类某个方法调用前、调用后、方法抛出异常后等。**连接点由两个信息确定:方法表示的程序执行点;相对点表示的方位**。 切点( pointcut ): **每个类都拥有多个连接点**:例如 ArithmethicCalculator 的所有方法实际上都是连接点,即 **连接点是程序类中客观存在的事务**。 **AOP 通过切点定位到特定的连接点。类比:连接点相当于数据库中的记录,切点相当于查询条件**。切点和连接点不是一对一的关系,一个切点匹配多个连接点,切点通过 org.springframework.aop.Pointcut 接口进行描述,它使用类和方法作为连接点的查询条件。 ## 启用AspectJ注解(基于注解) ## 要在 Spring 应用中使用 AspectJ 注解, **必须在 classpath 下包含 AspectJ 类库**:aopalliance.jar、aspectj.weaver.jar 和 spring-aspects.jar **将 aop Schema 添加到<beans> 根元素中**. 要在 Spring IOC 容器中启用 AspectJ 注解支持, 只要**在 Bean 配置文件中定义一个空的 XML 元素<aop:aspectj-autoproxy>** 当 Spring IOC 容器侦测到 Bean 配置文件中的 <aop:aspectj-autoproxy> 元素时, 会自动为与 AspectJ 切面匹配的 Bean 创建代理. 1、导入的jar包(见同类文章第一篇) 2、在配置文件中加入如下配置 <aop:aspectj-autoproxy></aop:aspectj-autoproxy> 把横切关注点的代码抽象到切面类中。 切面首先是一个IOC中的bean,及假日@Component注解 切面还需要加入@Aspect注解 3、在类中申明各种通知 申明一个方法 在方法前面加入@Before注解 4、可以在通知方法中声明一个类型为JoinPoint的参数,然后就能访问链接细节,入方法名称和参数值 // 通过添加 @Aspect 注解声明一个 bean 是一个切面! @Aspect @Component public class LoggingAspect { @Before("execution(* com.spring.aop.helloworld.*.*(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)); } } ## 利用方法签名编写 AspectJ 切入点表达式 ## 最典型的切入点表达式时根据方法的签名来匹配各种方法: 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 中, 切入点表达式可以通过操作符 &&, ||, ! 结合起来. ![20170611112016001][] 可以在通知方法中声明一个类型为 JoinPoint 的参数. 然后就能访问链接细节. 如方法名称和参数值 ![20170611112138252][] **JoinPoint:**标识这个方法是个前置通知, 切点表达式表示执行任意类的任意方法. 第一个 **\***代表匹配任意修饰符及任意返回值, 第二个**\***代表任意类的对象, 第三个**\***代表任意方法,参数列表中的 **..** 匹配任意数量的参数 ### 前置通知 ### 前置通知:在方法执行之前执行的通知 前置通知使用 @Before 注解, 并将切入点表达式的值作为注解值 ![20170611112404862][] 标识这个方法是个前置通知, 切点表达式表示执行 ArithmeticCalculator 接口的 add() 方法. \* 代表匹配任意修饰符及任意返回值, 参数列表中的 .. 匹配任意数量的参数 ### 后置通知 ### 后置通知是在连接点完成之后执行的,即连接点返回结果或者抛出异常的时候, 下面的后置通知记录了方法的终止. 一个切面可以包括一个或者多个通知. ![20170611112505613][] ### 返回通知 ### 无论连接点是正常返回还是抛出异常,后置通知都会执行. 如果只想在连接点返回的时候记录日志, 应使用返回通知代替后置通知 ![20170611112603207][] ### 异常通知 ### 只在连接点抛出异常时才执行异常通知 **将 throwing 属性添加到 @AfterThrowing 注解中**, 也可以访问连接点抛出的异常. Throwable 是所有错误和异常类的超类. 所以在异常通知方法可以捕获到任何错误和异常. **如果只对某种特殊的异常类型感兴趣**, 可以将参数声明为其他异常的参数类型. 然后通知就只在抛出这个类型及其子类的异常时才被执行 ![20170611112737021][] ### 环绕通知 ### ![20170611112839607][] xml配置 <context:component-scan base-package="com.spring.beans.aop.annotation"></context:component-scan> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> 测试类 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator"); System.out.println(arithmeticCalculator.getClass().getName()); int result = arithmeticCalculator.add(11, 12); System.out.println("result:" + result); ## 基于xml配置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); } 实现类 public class ArithmeticCalculatorImpl implements ArithmeticCalculator { public int add(int i, int j) { int result = i + j; return result; } public int sub(int i, int j) { int result = i - j; return result; } public int mul(int i, int j) { int result = i * j; return result; } public int div(int i, int j) { int result = i / j; return result; } } 定义切面 package com.spring.beans.aop.xml; import java.util.Arrays; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; public class LoggerAspect { public void beforeMethod(JoinPoint joinPoint) { String name = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); System.out.println("The method after" + name + " begins with" + Arrays.asList(args)); } public void afterMethod(JoinPoint joinPoint) { String name = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); System.out.println("The method div" + name + " begins with" + Arrays.asList(args)); } public void afterReturning(JoinPoint joinPoint) { String name = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); System.out.println("The method div" + name + " begins with" + Arrays.asList(args)); } public void afterThrowing(JoinPoint joinPoint, Exception e) { String name = joinPoint.getSignature().getName(); // Object[] args = joinPoint.getArgs(); System.out.println("The method div" + name + " begins with" + e); } public Object aroundMethod(ProceedingJoinPoint pjd) { Object r = null; String name = pjd.getSignature().getName(); try { // 前置通知 System.out.println("The method " + name + " begins with" + Arrays.asList(pjd.getArgs())); r = pjd.proceed(); // 后置通知 System.out.println("The method " + name + " ends with" + Arrays.asList(pjd.getArgs())); } catch (Throwable e) { e.printStackTrace(); System.out.println("The method " + name + " occurs with" + Arrays.asList(pjd.getArgs())); } return r; } } xml配置 <bean id="arithmeticCalculator" class="com.spring.beans.aop.xml.ArithmeticCalculatorImpl"> </bean> <bean id="loggerAspect" class="com.spring.beans.aop.xml.LoggerAspect"></bean> <bean id="validationAspect" class="com.spring.beans.aop.xml.ValidationAspect"> </bean> <!-- 配置aop --> <aop:config> <!-- 配置切点表达式 --> <aop:pointcut id="pointCut" expression="execution(* com.spring.beans.aop.xml.ArithmeticCalculator.*(*,*))" /> <!-- 配置切面及通知 --> <aop:aspect ref="loggerAspect" 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="validationAspect" order="1"> <aop:before method="validationAspect" pointcut-ref="pointCut" /> </aop:aspect> </aop:config> 测试类 ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext-xml.xml"); ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx .getBean("arithmeticCalculator"); System.out.println(arithmeticCalculator.getClass().getName()); int div = arithmeticCalculator.div(12, 0); System.out.println(div); } [Spring_1-1_xml_Bean]: http://blog.csdn.net/www1056481167/article/details/73008382 [20170611112016001]: /images/20220614/fdd132b1cab2473283bd5e61c54ddd8f.png [20170611112138252]: /images/20220614/21daffd3494e47f090c4a672ff1ac111.png [20170611112404862]: /images/20220614/462268958d104594bbc8d5a88c821161.png [20170611112505613]: /images/20220614/84688bb2c5274b6da6300631ab1bd22d.png [20170611112603207]: /images/20220614/a0465e27c3754673b8b8d82bc3b49349.png [20170611112737021]: /images/20220614/a16ee0b2e8f9443f92a94caf5596cdfa.png [20170611112839607]: /images/20220614/3852107247184d76b0129b7ff9d204b3.png
还没有评论,来说两句吧...