二.Spring的AOP
3.1、AOP 原理
1.需求
增加需求:
需求1-日志:在程序执行期间追踪正在发生的活动
需求2-验证:希望计算器只能处理正数的运算
2.代码实现片段
ICount 计算器接口
package com.cm.ch05.aop; public interface ICount { public int add(int i, int j); public int sub(int i, int j); public int mul(int i, int j); public int div(int i, int j); }
CountImpl 计算器实现类
package com.cm.ch05.aop; import org.springframework.stereotype.Component; @Component public class CountImpl implements ICount{ @Override public int add(int i, int j){ System.out.println("add()"); int result = i+j; return result; } @Override public int sub(int i, int j) { System.out.println("sub()"); int result = i-j; return result; } @Override public int mul(int i, int j) { System.out.println("mul()"); int result = i*j; return result; } @Override public int div(int i, int j) { System.out.println("div()"); int result = i/j; return result; } }
CountLogImpl 计算器日志实现类
package com.cm.ch05.aop; //添加需求:日志跟踪 public class CountLogImpl implements ICount{ @Override public int add(int i, int j) { System.out.println("日志追踪:the method add begin with [ "+i+","+j+" ]"); int result = i+j; System.out.println("日志追踪:the method add end with "+result); return result; } @Override public int sub(int i, int j) { System.out.println("日志追踪:the method sub begin with [ "+i+","+j+" ]"); int result = i-j; System.out.println("日志追踪:the method sub end with "+result); return result; } @Override public int mul(int i, int j) { System.out.println("日志追踪:the method mul begin with [ "+i+","+j+" ]"); int result = i*j; System.out.println("日志追踪:the method mul end with "+result); return result; } @Override public int div(int i, int j) { System.out.println("日志追踪:the method div begin with [ "+i+","+j+" ]"); int result = i/j; System.out.println("日志追踪:the method div end with "+result); return result; } }
问题:
1.代码混乱:越来越多的非业务需求(日志和验证等)加入后, 原有的业务方法急剧膨胀. 每个方法在处理核心逻辑的同时还必须兼顾其他多个关注点.
2.代码分散: 以日志需求为例, 只是为了满足这个单一需求, 就不得不在多个模块(方法)里多次重复相同的日志代码. 如果日志需求发生变化, 必须修改所有模块.
3.使用动态代理解决上述问题
代理设计模式的原理: 使用一个代理将对象包装起来, 然后用该代理对象取代原始对象. 任何对原始对象的调用都要通过代理. 代理对象决定是否以及何时将方法调用转到原始对象上.
ArithmeticCalculatorLogProxy动态代理类
public class ArithmeticCalculatorLogProxy { // ArithmeticCalculatorLogProxy动态代理类 //要代理的对象 private ArithmeticCalculator target; public ArithmeticCalculatorLogProxy(ArithmeticCalculator target){ this.target = target; } public ArithmeticCalculator getLogProxy(){ ArithmeticCalculator proxy = null; //代理对象由哪一个类加载器负责加载 ClassLoader loader = target.getClass().getClassLoader(); //代理对象的类型 Class[] interfaces = new Class[]{ArithmeticCalculator.class}; //当调用代理对象其中的方法时,该执行的代码 InvocationHandler h = new InvocationHandler() { /** * proxy:正在返回的那个代理对象。一般情况下在invoke方法中不使用该对象 * method:正在被调用的方法 * args:调用方法时,传入的参数 */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); //日志 System.out.println("the method "+methodName+" begin with "+Arrays.asList(args)); //执行方法 Object result = method.invoke(target, args); //日志 System.out.println("the method "+methodName+" end with "+result); return result; } }; proxy = (ArithmeticCalculator)Proxy.newProxyInstance(loader, interfaces, h); return proxy; } }
测试
ArithmeticCalculator target = new ArithmeticCalculatorImpl(); ArithmeticCalculator proxy = new ArithmeticCalculatorLogProxy(target).getLogProxy(); int result = proxy.add(1, 2); System.out.println("-->"+result); result = proxy.div(4, 2); System.out.println("-->"+result);
3.2、AOP 简介
1.AOP(Aspect-Oriented Programming, 面向切面编程)
是一种新的方法论, 是对传统 OOP(Object-Oriented Programming, 面向对象编程) 的补充.
AOP 的主要编程对象是切面(aspect), 而切面模块化横切关注点.
在应用 AOP 编程时,仍然需要定义公共功能, 但可以明确的定义这个功能在哪里, 以什么方式应用, 并且不必修改受影响的类. 这样一来横切关注点就被模块化到特殊的对象(切面)里.
2.AOP的好处
1). 每个事物逻辑位于一个位置, 代码不分散, 便于维护和升级
2). 业务模块更简洁, 只包含核心业务代码.
3.AOP术语
1). 切面(Aspect): 横切关注点(跨越应用程序多个模块的功能)被模块化的类
2). 通知(Advice): 切面必须要完成的工作(切面中的每一个方法被称为通知)
3). 目标(Target): 被通知的对象
4). 代理(Proxy): 向目标对象应用通知之后创建的对象
5). 连接点(Joinpoint):程序执行的某个特定位置(一个具体的物理存在):如类某个方法调用前、调用后、方法抛出异常后等。连接点由两个信息确定:方法表示的程序执行点;相对点表示的方位。例如 ArithmethicCalculator#add() 方法执行前的连接点,执行点为 ArithmethicCalculator#add(); 方位为该方法执行前的位置
6). 切点(pointcut):每个类都拥有多个连接点:例如 ArithmethicCalculator 的所有方法实际上都是连接点,即连接点是程序类中客观存在的事务。AOP 通过切点定位到特定的连接点。类比:连接点相当于数据库中的记录,切点相当于查询条件。切点和连接点不是一对一的关系,一个切点匹配多个连接点,切点通过 org.springframework.aop.Pointcut 接口进行描述,它使用类和方法作为连接点的查询条件。
3.3、Spring AOP 注解+XML版
1).AspectJ:Java 社区里最完整最流行的 AOP 框架.
2).在 Spring2.0 以上版本中, 可以使用基于 AspectJ 注解或基于 XML 配置的 AOP
1.在 Spring 中启用 AspectJ 注解支持,修改pom.xml
<!-- 引入spring的AOP依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.2.6.RELEASE</version> </dependency> <!-- 引入aspectj依赖 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency>
2.新建spring的核心配置文件
要在 Spring IOC 容器中启用 AspectJ 注解支持, 只要在 Bean 配置文件中定义一个空的 XML 元素 aop:aspectj-autoproxy。当 Spring IOC 容器侦测到 Bean 配置文件中的 aop:aspectj-autoproxy 元素时, 会自动为与 AspectJ 切面匹配的 Bean 创建代理。
<?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 https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 支持注解配置 --> <context:component-scan base-package="com.cm.ch05.aop" /> <!-- 支持AOP框架 --> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
3.用 AspectJ 注解声明切面
1).要在 Spring 中声明 AspectJ 切面, 只需要在 IOC 容器中将切面声明为 Bean 实例. 当在 Spring IOC 容器中初始化 AspectJ 切面之后, Spring IOC 容器就会为那些与 AspectJ 切面相匹配的 Bean 创建代理.
2).在 AspectJ 注解中, 切面只是一个带有 @Aspect 注解的 Java 类.
3).通知是标注有某种注解的简单的 Java 方法.
4).AspectJ 支持 5 种类型的通知注解:
@Before: 前置通知, 在方法执行之前执行
@After: 后置通知, 在方法执行之后执行
@AfterReturning: 返回通知, 在方法返回结果之后执行
@AfterThrowing: 异常通知, 在方法抛出异常之后
@Around: 环绕通知, 围绕着方法执行
4.通知
1).前置通知
在方法执行之前执行的通知,前置通知使用 @Before 注解, 并将切入点表达式的值作为注解值.
2).后置通知
@After是在连接点完成之后执行的, 即连接点返回结果或者抛出异常的时候, 下面的后置通知记录了方法的终止.
3).返回通知
无论连接点是正常返回还是抛出异常, 后置通知都会执行. 如果只想在连接点返回的时候记录日志, 应使用返回通知代替后置通知.
在返回通知中访问连接点的返回值
1).在返回通知中, 只要将 returning 属性添加到 @AfterReturning 注解中, 就可以访问连接点的返回值. 该属性的值即为用来传入返回值的参数名称.
2).必须在通知方法的签名中添加一个同名参数. 在运行时, Spring AOP 会通过这个参数传递返回值.
3).原始的切点表达式需要出现在 pointcut 属性中
4).异常通知
1).只在连接点抛出异常时才执行异常通知
2).将 throwing 属性添加到 @AfterThrowing 注解中, 也可以访问连接点抛出的异常. Throwable 是所有错误和异常类的超类. 所以在异常通知方法可以捕获到任何错误和异常.
3).如果只对某种特殊的异常类型感兴趣, 可以将参数声明为其他异常的参数类型. 然后通知就只在抛出这个类型及其子类的异常时才被执行.
5).环绕通知
1). 环绕通知@Around是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点.
2).对于环绕通知来说, 连接点的参数类型必须是 ProceedingJoinPoint . 它是 JoinPoint 的子接口, 允许控制何时执行, 是否执行连接点.
3).在环绕通知中需要明确调用 ProceedingJoinPoint 的 proceed() 方法来执行被代理的方法. 如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行.
4).注意: 环绕通知的方法需要返回目标方法执行之后的结果, 即调用 joinPoint.proceed(); 的返回值, 否则会出现空指针异常
5.利用方法签名编写 AspectJ 切入点表达式
1).execution * com.etc.spring.ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 中声明的所有方法,第一个 * 代表任意修饰符及任意返回值. 第二个 * 代表任意方法. .. 匹配任意数量的参数. 若目标类与接口与该切面在同一个包中, 可以省略包名.
2).execution public * ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 接口的所有公有方法.
3).execution public double ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 中返回 double 类型数值的方法
4).execution public double ArithmeticCalculator.*(double, ..): 匹配第一个参数为 double 类型的方法, .. 匹配任意数量任意类型的参数
5).execution public double ArithmeticCalculator.*(double, double): 匹配参数类型为 double, double 类型的方法.
6.指定切面的优先级
1).在同一个连接点上应用不止一个切面时, 除非明确指定, 否则它们的优先级是不确定的.
2).切面的优先级可以通过实现 Ordered 接口或利用 @Order 注解指定.
3).实现 Ordered 接口, getOrder() 方法的返回值越小, 优先级越高.
4).若使用 @Order 注解, 序号出现在注解
7.重用切入点定义
1).在编写 AspectJ 切面时, 可以直接在通知注解中书写切入点表达式. 但同一个切点表达式可能会在多个通知中重复出现.
2).在 AspectJ 切面中, 可以通过 @Pointcut 注解将一个切入点声明成简单的方法. 切入点的方法体通常是空的, 因为将切入点定义与应用程序逻辑混在一起是不合理的.
3).切入点方法的访问控制符同时也控制着这个切入点的可见性。如果切入点要在多个切面中共用, 最好将它们集中在一个公共的类中. 在这种情况下, 它们必须被声明为 public. 在引入这个切入点时, 必须将类名也包括在内. 如果类没有与这个切面放在同一个包中, 还必须包含包名.
4).其他通知可以通过方法名称引入该切入点.
8.案例
一个切面可以包括一个或者多个通知.
package com.cm.ch05.aop; import java.util.Arrays; import java.util.List; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /* * 日志切面 * 切面:横切关注点 * 1.将当前类添加到IOC容器中:@Component * 2.将当前类可以进行使用AOP:@Aspect * 3.@Order(2) 切面的优先级,数值越小越先执行 */ @Order(2) @Component @Aspect public class LogAspect { //公共切入点:通过 @Pointcut 注解将一个切入点声明成简单的方法. 切入点的方法体通常是空的 @Pointcut("execution(public int com.cm.ch05.aop.CountImpl.*(int,int))") public void declarePointcut(){} /* * 前置通知:@Before("execution(public int com.cm.ch05.aop.CountImpl.*(int,int))") * 1.@Before * 2.切点pointcut:("execution(xxx)") * 3.简化的语法:@Before("execution(* CountImpl.*(..))") * 第一个*:任意访问权限和任意返回值 * 第二个*:指定类下的任意方法 * 第三个..:匹配任意参数 * PS:同包下,包名可省略 * 4.JoinPoint 连接点:获得当前正在访问的方法名,参数列表 */ //@Before("execution(* CountImpl.*(..))") @Before("declarePointcut()") public void beforeAdvice(JoinPoint jp){ //方法名 String methodName = jp.getSignature().getName(); //参数列表 List<Object> args = Arrays.asList(jp.getArgs()); System.out.println("日志追踪:the method "+methodName+" begin with "+args); } //返回通知:returning值的名字必须与方法中参数的形参名字一致 //@AfterReturning(pointcut="execution(* CountImpl.*(..))",returning="result") @AfterReturning(pointcut="declarePointcut()",returning="result") public void AfterReturningAdvice(JoinPoint jp,Object result) throws Throwable{ //方法名 String methodName = jp.getSignature().getName(); System.out.println("日志追踪:the method "+methodName+" end with "+result); } //异常通知:throwing值的名字必须与方法中参数的形参名字一致 //@AfterThrowing(value="execution(* CountImpl.*(..))",throwing="ex") @AfterThrowing(pointcut="declarePointcut()",throwing="ex") public void AfterThrowingAdvice(JoinPoint jp,Exception ex){ //方法名 String methodName = jp.getSignature().getName(); System.out.println("日志追踪:the method "+methodName+" occurn exception:"+ex); } //后置通知 //@After("execution(* CountImpl.*(..))") @After("declarePointcut()") public void AfterAdvice(JoinPoint jp){ //方法名 String methodName = jp.getSignature().getName(); System.out.println("日志追踪:the method "+methodName+" end with"); } //环绕通知 //@Around("execution(* CountImpl.*(..))") public Object AroundAdvice(ProceedingJoinPoint pjp){ String methodName = pjp.getSignature().getName(); List<Object> args = Arrays.asList(pjp.getArgs()); Object result = null; try { //前置通知 System.out.println("日志追踪:the method "+methodName+" begin with "+args); result = pjp.proceed(); //返回通知 System.out.println("日志追踪:the method "+methodName+" end with "+result); } catch (Throwable e) { //环绕通知 System.out.println("日志追踪:the method "+methodName+" occurs exception:"+e.getMessage()); } //后置通知 System.out.println("日志追踪:the method "+methodName+" end with"); return result; } }
9.测试
package com.cm.ch05.aop; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("beans_aop.xml"); ICount count = (ICount)ac.getBean("countImpl"); System.out.println(count.getClass().getName()); int result1 = count.add(1, 2); System.out.println(result1); int result2 = count.div(0, 2); System.out.println(result2); } }
3.4、Spring AOP XML版
1.基于 XML ---- 声明切面
1.当使用 XML 声明切面时, 需要在 <beans> 根元素中导入 aop Schema
2.在 Bean 配置文件中, 所有的 Spring AOP 配置都必须定义在 aop:config 元素内部. 对于每个切面而言, 都要创建一个 aop:aspect 元素来为具体的切面实现引用后端 Bean 实例.
3.切面 Bean 必须有一个标示符, 供 aop:aspect 元素引用
2.基于 XML ---- 声明切入点
1.切入点使用aop:pointcut元素声明
2.切入点必须定义在 aop:aspect 元素下, 或者直接定义在 aop:config 元素下.
1).定义在 aop:aspect 元素下: 只对当前切面有效
2).定义在 aop:config 元素下: 对所有切面都有效
3.基于 XML 的 AOP 配置不允许在切入点表达式中用名称引用其他切入点.
3.基于 XML ---- 声明通知
1.在 aop Schema 中, 每种通知类型都对应一个特定的 XML 元素.
2.通知元素需要使用 <pointcut-ref> 来引用切入点, 或用 <pointcut> 直接嵌入切入点表达式. method 属性指定切面类中通知方法的名称.
3.5、Spring AOP 配置类+注解版
MyConfig类
//开启Aspect面向切面编程 proxyTargetClass = true开启CGLIB动态代理 @EnableAspectJAutoProxy(proxyTargetClass = true) //配置扫描包 @ComponentScan("com.igeek.aop.ch03.config") //当前类是一个配置类 @Configuration public class MyConfig { /** * @Bean 注解 * 1.将当前方法的返回值放入IOC容器进行管理 * 2.无论getBean多少次,获得都是唯一的实例,因为Spring IOC容器,默认单实例 * 3.当前实例放入IOC容器后,会将当前方法名作为BeanName来进行使用 * 4.@Bean在配置类,搭配创建组件 */ //@Scope("prototype") @Bean public ArithmeticCalculator c(){ return new ArithmeticCalculator(); } }
Test类
public class Test { public static void main(String[] args) { //1.创建IOC容器 AnnotationConfigApplicationContext ApplicationContext ac = new AnnotationConfigApplicationContext(MyConfig.class); //2.获得实例bean ArithmeticCalculator proxy = ac.getBean(ArithmeticCalculator.class); //com.igeek.aop.ch03.config.ArithmeticCalculator$$EnhancerBySpringCGLIB$$b304c68a System.out.println(proxy.getClass().getName()); //3.使用实例bean int result1 = proxy.add(10, 20); System.out.println("result1 = "+result1); int result2 = proxy.div(-10, 5); System.out.println("result2 = "+result2); } }