springboot 做切面
1. 引入依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2.书写目标方法
@Component //放入容器 public class User { public String eat(String food) { System.out.println("吃"+food); return "吃饱了"; } }
3.书写切面类和方法
@Aspect @Component public class CutPoint { /** * 声明一个切面 */ @Pointcut(value ="execution(* com.example.domain.*.*(..))" ) public void pc() { } @Before(value = "pc()") public void before() { System.out.println("饭前水果"); } @After(value="pc()") public void after() { System.out.println("饭后来一根烟"); } @Around(value = "pc()") public void arroud(ProceedingJoinPoint joinPoint) { try { Object[] args = joinPoint.getArgs(); // 获取参数 for (Object object : args) { System.out.println(object); } before(); joinPoint.proceed(); //执行原方法 Object proceed = joinPoint.proceed(); //获取返回值 System.out.println(proceed); after(); } catch (Throwable e) { e.printStackTrace(); } } @AfterThrowing(value="pc()",throwing = "tw") public void error(Throwable tw) { System.out.println("目标出现异常!"); //捕获异常 } }