SpringBoot中AOP的如何使用?
1、准备多个Controller
package com.base.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class HelloController {
@RequestMapping("/hello")
public String hello() {
log.info("hello");
return "hello";
}
}
package com.base.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class TestController {
@RequestMapping("/test")
public String hello() {
log.info("test");
return "test";
}
}
2、引入jar
<!--aop 切面-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
3、定义切点与通知
package com.base.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* 定义切点与通知
*/
@Aspect
@Component
@Slf4j
public class AopConfig {
/**
* 切点
*/
@Pointcut("execution (* com.base.controller.*.*(..))")
public void helloWorld() {
}
/**
* 通知
*/
@Before("helloWorld()")
public void beforeAdvice() {//前置通知
log.info("...beforeAdvice...");
}
@After("helloWorld()")
public void afterAdvice() {//后置通知
log.info("...afterAdvice...");
}
@Around("helloWorld()")
public void aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {//环绕通知
log.info("...aroundBeforeAdvice...");
proceedingJoinPoint.proceed();
log.info("...aroundAfterAdvice...");
}
}
4、测试
http://localhost:8001/hello
http://localhost:8001/test