aop:面向切面编程,理解在一个流程中插入一个切面,这样切面方法会在指定位置执行
能无影响的在某些方法前或者后插入一些动作
springboot使用
1.引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>
2.随便定义一个类,随便写一个方法,需要加注解@Aspect @Component交由ioc容器管理
在方法里加@Around属性指定方法
@Aspect
@Component
public class DemoAspect {@Around("execution(void com.example.demo.DemoApplication.test())")public Object surround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {System.out.println("before");return proceedingJoinPoint.proceed();}}
这样在test方法执行前会先执行输出before
before
org.dom4j.io.SAXReader@30a6b57d
2025-07-12T19:35:23.818+08:00 ERROR 8512 --- [demo] [nio-9999-exec-8] com.example.demo.MyException : error:No static resource favicon.ico.
有些专用名词
@Aspect
:用于声明一个类为切面。@Component
:将切面类作为Spring管理的组件。@Before
、@After
、@Around
、@AfterThrowing
、@AfterReturning
:用于定义不同类型的通知。
表达式可以使用 * 和 .. 代表一个词和任意多个词 例如:com.example.service.*.*(..))