AOP 在实际项目中的应用
1 AOP简介
1.1AOP基本概念
AOP(Aspect Oriented Programming)面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容。
1.2 AOP的作用
AOP的核心作用是:在程序运行期间,不修改代码的同时为程序增强功能。将必不可少的公共功能做成切面,随着程序运行切入到代码中运行。编写业务时只关注于核心功能 ,不再考虑事务、日志等公共功能,减轻了编码负担,更专注于业务。
1.3 AOP的术语
1、切面(Aspect)
对哪些方法进行拦截,拦截后怎么处理,这些关注点称之为切面
2、连接点(joinpoint)
被拦截到的点,因为Spring只支持方法类型的连接点,所以在Spring中连接点指的就是被拦截到的方法,实际上连接点还可以是字段或者构造器
3、切入点(pointcut)
对连接点进行拦截的定义
4、通知(advice)
所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类
5、目标对象(target)
代理的目标对象,将切面应用到目标对象并导致代理对象创建的过程
6、引入\织入(introduction、weave)
在不修改代码的前提下,引入可以在运行期为类动态地添加一些方法或字段
2 AOP实现
2.1 AOP普通配置
2.1.1 引入依赖
在项目的pom.xml中导入需要的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
2.1.2 编写通知类
编写代码运行时所需要的通知信息类
import org.aspectj.lang.ProceedingJoinPoint;
public class LogAdvise {
public void beforeLog(){
System.out.println("方法开始执行!");
}
public void afterLog(){
System.out.println("方法后置执行!");
}
public void afterReturning(){
System.out.println("方法返回了数据");
}
public void afterThrowing(){
System.out.println("方法抛出了异常");
}
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("around方法名:" + joinPoint.getSignature().getName());
System.out.println("around --前置");
//原来方法
joinPoint.proceed();
System.out.println("around --后置");
}
}
2.1.3添加配置文件
在resources文件夹下添加spring_aop配置文件
<?xml version=