1、添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2、设置切面
@Aspect @Configuration public class AopConfig { @Pointcut("execution(* com.glodon.springboot.controller.AopController.test*(..))") public void excudeService(){} @Before("excudeService()") public void before() { System.out.println("切面before执行了"); } @After("excudeService()") public void after() { System.out.println("切面after执行了"); } @AfterReturning("excudeService()") public void afterReturning() { System.out.println("切面afterReturning执行了"); } @AfterThrowing("excudeService()") public void afterThrowing() { System.out.println("切面afterThrowing执行了"); } @Around("excudeService()") public Object around(ProceedingJoinPoint thisJoinPoint){ Object obj = null; System.err.println ("切面around before执行了"); try { thisJoinPoint.proceed(); } catch (Throwable e) { e.printStackTrace (); } System.err.println ("切面around after执行了"); return obj; } }
3、测试类
@RestController @RequestMapping(value = "/api/aop") public class AopController { @GetMapping(value = "/test") public String testAOP() { System.out.println("test"); return "test"; } }
4、AOP顺序
通过注解方式配置AOP是无序的,若想有序则需显式定义一个Advisor的实现了Ordered的子类的bean,并且给order赋值
更多: