目录
Spring AOP(面向切面编程)是Spring框架中的一个模块,用于将与业务逻辑无关的横切关注点与核心业务逻辑分离。横切关注点是影响应用程序多个部分的功能,比如日志记录、安全性、事务管理和错误处理等。
一、Spring AOP 的核心概念
1. 切面(Aspect)
封装横切关注点的模块。在Spring中,切面使用 @Aspect 注解来定义。
2. 连接点(Join Point)
程序执行过程中的一个点,通常是方法执行。Spring AOP中的连接点主要是方法执行。
3.通知(Advice)
在某个连接点执行的操作。Spring AOP中的通知有几种类型:
(1)前置通知(Before): 在方法执行前运行的通知。
(2)后置通知(After): 在方法执行后运行的通知(无论方法是成功还是异常)。
(3)返回后通知(After Returning): 在方法成功完成后运行的通知。
(4)异常后通知(After Throwing): 在方法抛出异常时运行的通知。
(5)环绕通知(Around): 包含方法执行的通知,可以在方法调用前后执行代码。
4. 切入点(Pointcut)
一个表达式,用于选择通知应用的连接点。切入点定义了通知的执行位置。
5. 织入(Weaving)
将切面与其他应用类型或对象连接在一起以创建一个织入对象的过程。织入可以在编译时、类加载时或运行时发生。
二、Spring AOP 示例
1.添加依赖
使用Maven,在pom.xml中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.定义一个切面
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.demo.service.*.*(..))")
public void logBeforeMethod() {
System.out.println("方法即将被调用");
}
}
在上面的示例中,logBeforeMethod()通知将在com.example.demo.service包中的任何方法执行之前执行。
3.创建一个服务类
import org.springframework.stereotype.Service;
@Service
public class MyService {
public void performTask() {
System.out.println("正在执行任务...");
}
}
4.主应用程序
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public CommandLineRunner demo(MyService myService) {
return args -> {
myService.performTask();
};
}
}