AOP简介和测试
来源:互联网 发布:微信会员卡源码 编辑:程序博客网 时间:2024/06/06 20:44
AOP简介
AOP,即面向切面编程,它是Spring中的两个重要内容之一。它是为了把逻辑代码和处理琐碎事务的代码分离开,以便能够分离复杂度。
设想这样一种需求:要实现一个计算器,除了能够进行加减乘除运算之外,还有两个功能,一是日志功能,即能够记录程序的执行情况;二是验证功能,即对要计算的参数进行验证。
传统的实现方法是在每一个方法上都添加日志和验证功能,例如,对于日志功能,实现代码如下:
这将导致的问题有:
1. 代码混乱:越来越多的非业务需求(日志和验证等)加入后,原有的业务方法急剧膨胀,每个方法在处理核心逻辑的同时还必须兼顾其他多个关注点。
2. 代码分散: 以日志需求为例,只是为了满足这个单一需求,就不得不在多个模块(方法)里多次重复相同的日志代码,如果日志需求发生变化,必须修改所有模块。
这正是AOP可以解决的问题,AOP的主要编程对象是切面(Aspect),切面可以模块化横切关注点,例如,上述例子中的日志和验证功能都可以被模块化到特定的切面类中。AOP解决上述问题的原理如下图所示:
AOP中的相关术语如下:
现在我们以上述问题为例,来简单测试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);}//计算器实现类@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; }}
Spring中有两种方式用以实现AOP,一种是基于AspectJ注解的方式,另一种是基于XML配置文件的方式,下面逐一介绍。
基于AspectJ注解的方式
首先导入AspectJ的jar包:
编写分别负责日志和验证功能的两个切面类:
//日志切面//@Order指明切面的优先级,值越小优先级越高@Order(2)//通过添加 @Aspect 注解声明一个 bean 是一个切面@Aspect@Componentpublic class LoggingAcpect { /** * 定义一个方法, 用于声明切入点表达式. 一般地, 该方法中再不需要添入其他的代码. * 使用 @Pointcut 来声明切入点表达式. * 后面的其他通知直接使用方法名来引用当前的切入点表达式. */ @Pointcut("execution(* com.MySpring.aop.annotation.*.*(..))") public void declareJointPointExpression(){} /** * 前置通知: * 在 com.MySpring.aop.annotation 包下的每一个类的每一个方法开始之前执行一段代码 */ @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)); } /** * 后置通知: * 在 com.MySpring.aop.annotation 包下的每一个类的每一个方法开始后执行一段代码 * 无论这段代码是否抛出异常 */ @After("declareJointPointExpression()") public void afterMethod(JoinPoint joinpoint){ String methodName = joinpoint.getSignature().getName(); Object[] args = joinpoint.getArgs(); System.out.println("the method "+methodName+" ends"); } /** * 返回通知: * 在方法法正常结束受执行的代码 * 返回通知是可以访问到方法的返回值的! */ @AfterReturning(value="declareJointPointExpression()",returning="result") public void afterReturning(JoinPoint joinpoint,Object result){ String methodName = joinpoint.getSignature().getName(); Object[] args = joinpoint.getArgs(); System.out.println("the method "+methodName+" ends with result "+result); } /** * 异常通知: * 在目标方法出现异常时会执行的代码. * 可以访问到异常对象; 且可以指定在出现特定异常时在执行通知代码 */ @AfterThrowing(value="declareJointPointExpression()",throwing="e") public void afterThrowing(JoinPoint joinpoint,Exception e){ String methodName = joinpoint.getSignature().getName(); Object[] args = joinpoint.getArgs(); System.out.println("the method "+methodName+" occurs exception "+e); }}//验证切面@Order(1)@Aspect@Componentpublic class ValidationAspect { @Pointcut("execution(* com.MySpring.aop.annotation.*.*(..))") public void declareJointPointExpression(){} @Before("declareJointPointExpression()") public void validateArgs(JoinPoint joinPoint){ Object[] args = joinPoint.getArgs(); System.out.println("-->validate args "+Arrays.asList(args)); }}
编写spring配置文件applicationContext-aop-annotation.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/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"> <!-- 配置自动扫描的包 --> <context:component-scan base-package="com.MySpring.aop"></context:component-scan> <!-- 配置自动为匹配 aspectJ 注解的 Java 类生成代理对象 --> <aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>
编写测试类:
public class Test { @org.junit.Test public void test() { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-aop-annotation.xml"); ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator"); System.out.println("result is "+arithmeticCalculator.add(100, 200)); System.out.println("result is "+arithmeticCalculator.div(100, 0)); }}运行结果:![image_1b51tt9lh1cl9f228c3i6u34s1t.png-26.2kB][5]
基于XML配置文件的方式
首先新建接口和类,和上面类似,只是没有AspectJ的注解:
//日志切面public class LoggingAcpect { 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)); } public void afterMethod(JoinPoint joinpoint){ String methodName = joinpoint.getSignature().getName(); Object[] args = joinpoint.getArgs(); System.out.println("the method "+methodName+" ends"); } public void afterReturning(JoinPoint joinpoint,Object result){ String methodName = joinpoint.getSignature().getName(); Object[] args = joinpoint.getArgs(); System.out.println("the method "+methodName+" ends with result "+result); } public void afterThrowing(JoinPoint joinpoint,Exception e){ String methodName = joinpoint.getSignature().getName(); Object[] args = joinpoint.getArgs(); System.out.println("the method "+methodName+" occurs exception "+e); }}//验证切面public class ValidationAspect { public void validateArgs(JoinPoint joinPoint){ Object[] args = joinPoint.getArgs(); System.out.println("-->validate args "+Arrays.asList(args)); }}
编写spring配置文件applicationContext-aop-xml.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/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"> <!-- 配置自动扫描的包 --> <context:component-scan base-package="com.MySpring.aop.xml"></context:component-scan> <!-- 配置切面的 bean. --> <bean id="loggingAspect" class="com.MySpring.aop.xml.LoggingAcpect"></bean> <bean id="validationAspect" class="com.MySpring.aop.xml.ValidationAspect"></bean> <!-- 配置 AOP --> <aop:config> <!-- 配置切点表达式 --> <aop:pointcut expression="execution(* com.MySpring.aop.xml.*.*(..))" id="pointcut" /> <!-- 配置切面及通知 --> <aop:aspect ref="loggingAspect" order="2"> <aop:before method="beforeMethod" pointcut-ref="pointcut" /> <aop:after method="afterMethod" pointcut-ref="pointcut" /> <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result" /> <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e" /> </aop:aspect> <aop:aspect ref="validationAspect" order="1"> <aop:before method="validateArgs" pointcut-ref="pointcut" /> </aop:aspect> </aop:config></beans>
编写测试类:
public class Test { @org.junit.Test public void test() { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-aop-xml.xml"); ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator"); System.out.println("result is "+arithmeticCalculator.add(100, 200)); System.out.println("result is "+arithmeticCalculator.div(100, 0)); }}
运行结果:
- AOP简介和测试
- Sysbench简介和测试
- MySQLSlap简介和测试
- Spring学习09-- AOP简介和使用
- AOP简介和基本概念【理解】【重点】
- aop简介
- AOP简介
- 【AOP】简介
- AOP简介
- AOP简介
- AOP简介
- Alpha和Beta测试简介
- Alpha和Beta测试简介
- 黑盒测试和白盒测试简介
- Alpha测试和Beta测试简介
- Alpha测试和Beta测试简介
- Spring 框架简介(Spring AOP 和 IOC 容器入门)
- Spring教程____Spring简介(核心IOC和AOP)
- 谈软件测试的心得
- repo
- IONIC 发布正式版本打包步骤
- JSON web token@00#abstract
- solr score打分模式及其问题
- AOP简介和测试
- SpringBatch的基本工作流程(二)
- printf系列和vprintf系列库函数详解
- JSON web token@01#介绍
- Te
- Thinkphp中的eq比较标签
- spring MVC 环境配置问题
- Java中Sytem.arraycopy()函数的使用
- 高德地图-地图中心固定Marker,Marker跳跃、掉落、生长动画