啥叫AOP?:
AOP(Aspect Oriented Programming)是一种设计思想,是软件设计领域中的面向切面编程,它是面向对象编程的一种补充和完善,它以通过预编译方式和运行期动态代理方式实现在不修改源代码的情况下给程序动态统一添加额外功能的一种技术。
注意用注解的AOP其中xml配置文件需要引入以下头文件,不然扫描和开启AOP会报异常。
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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-4.3.xsd">
1.在IOC所需依赖基础上再加入下面依赖即可:
<!-- spring-aspects会帮我们传递过来aspectjweaver -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.1</version>
</dependency>
其中IOC所需依赖如下:
<dependencies>
<!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version> </dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
2.将目标类和切面类都需要交给IOC容器管理,即在这两个类上面加上@componet。同时在切面类上面加上@Aspect注解进行标识
3.组件都必须要经过扫描,要在配置文件中添加如下代码,不然上面的component就无法被知晓。
<context:component-scan base-package="com.atguigu.aop.annotation"> </context:component-scan>
4.开启aop功能
5.在LoggerAspect切面类中写代码即再不改变目标代码的基础上增强目标对象的可扩张性(5种方法)
第一种方法:使用@Before注解标识,在被代理的目标方法执行前执行
第二种方法:使用@AfterReturning注解标识,在被代理的目标方法成功结束后执行
第三种方法:使用@After注解标识,在被代理的目标方法最终结束后执行即是在finally里面执行的通知。
第四种方法:使用@AfterThrowing注解标识,在被代理的目标方法异常结束后执行即是在捕获异常的内部即catch内部执行的通知。
第五种方法:使用使用try…catch…finally结构围绕整个被代理的目标方法,包括上面四种通知对应的所有位置
6.切面的优先级
相同目标方法上同时存在多个切面时,切面的优先级控制切面的内外嵌套顺序。
在切面类上使用@Order注解可以控制切面的优先级(所有切面的优先级默认值都是整数的最大值):
@Order(较小的数):优先级高
@Order(较大的数):优先级低
最后赋一张小实例的整体框架图