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.*.*(..))