Spring AOP快速入门:面向切面编程实战指南
Spring AOP快速入门:面向切面编程实战指南
1. AOP概述
1.1 什么是AOP
AOP(Aspect Oriented Programming)即面向切面编程,是Spring框架的核心之一。它是一种编程思想,主要用于处理系统中分布于各个模块的横切关注点,如日志记录、事务管理等。
面向切面编程的核心思想是将这些横切关注点从业务逻辑中分离出来,形成独立的模块(切面),从而实现代码的解耦和复用。
1.2 什么是Spring AOP
AOP作为一种思想,其具体实现方式有多种,如Spring AOP、AspectJ、CGLIB等。Spring AOP是其中一种实现方式,它允许在运行时对方法进行增强,而无需修改源代码。
在实际开发中,我们经常会遇到需要对多个方法进行相同处理的情况,例如记录方法执行时间。如果为每个方法都添加相同的代码,不仅会增加代码量,还会导致代码重复。此时,AOP就可以发挥作用,它可以在不修改原始代码的情况下,对目标方法进行功能增强。
2. Spring AOP入门
2.1 环境设置
要使用Spring AOP,首先需要在项目中引入相关依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
此外,还可以引入Lombok来简化代码,但需要注意在新版本中需要对Lombok的配置进行一些调整。
2.2 代码编写
下面是一个使用AOP记录方法执行时间的示例:
@Slf4j
@Aspect
@Component
public class TimeAspect {
@Around("execution(* com.example.springaop.controller.*.*(..))")
public Object timeRecord(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object proceed = joinPoint.proceed();
long end = System.currentTimeMillis();
log.info("耗时时间: " + (end - start) + "ms");
return proceed;
}
}
3. Spring AOP详细
3.1 Spring AOP核心概念
切点(Pointcut):定义了哪些方法需要被AOP拦截。例如:
execution(* com.example.springaop.controller.*.*(..))连接点(Join Point):满足切点表达式的所有方法。在上述例子中,所有Controller类中的方法都是连接点。
通知(Advice):具体要执行的逻辑。例如记录方法执行时间。
切面(Aspect):切面由切点和通知组成,描述了AOP需要针对哪些方法,在什么时候执行什么操作。
3.2 Spring AOP通知类型
Spring AOP支持多种通知类型:
@Around:环绕通知,在目标方法前后都会执行。@Before:前置通知,在目标方法前执行。@After:后置通知,在目标方法后执行,无论是否有异常都会执行。@AfterReturning:返回后通知,在目标方法正常返回后执行。@AfterThrowing:异常后通知,在目标方法抛出异常后执行。
3.3 @Pointcut注解
为了减少代码重复,可以使用@Pointcut注解提取公共的切点表达式:
@Pointcut("execution(* com.example.springaop.controller.*.*(..))")
public void pt() {}
@Around("pt()")
public Object aroundTest(ProceedingJoinPoint point) throws Throwable {
log.info("Around 开始执行");
Object result = point.proceed();
log.info("Around 结束执行");
return result;
}
3.4 @Order切面优先级
当存在多个切面时,可以通过@Order注解控制切面的执行顺序:
@Component
@Aspect
@Order(3)
public class AspectDemo3 {
@Before("com.example.springaop.aspect.AspectDemo1.pt()")
public void doBefore() {
log.info("AspectDemo3 do before...");
}
}
4. 总结
本文介绍了Spring AOP的基本概念、入门方法以及核心概念。通过AOP,可以实现代码的解耦和复用,减少重复代码,提高开发效率和维护性。