Springboot Aop整合
-
创建Springboot项目
-
pom.xml
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!-- aspectjrt和aspectjweaver是与aspectj相关的包,用来支持切面编程的; aspectjrt包是aspectj的runtime包; aspectjweaver是aspectj的织入包;--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.13</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> <!-- https://mvnrepository.com/artifact/cglib/cglib --> <!-- cglib包是用来动态代理用的,基于类的代理;--> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies>
-
Controller
@RestController @RequestMapping("/aop") public class AopController { @GetMapping("/index") public String index(){ return "hello spring Aop"; } }
-
aop
/* 把普通pojo实例化到spring容器中,相当于配置文件中的 */ @Aspect @Component public class WebLogAspect { private Logger logger= LoggerFactory.getLogger(WebLogAspect.class); /** * 定义切入点,切入点为com.lucas.Controller下的所有函数 */ @Pointcut("execution(public * com.lucas.Controller..*.*(..))") public void webLog(){ } @Before("webLog()") public void doBefore(JoinPoint joinPoint)throws Throwable { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //记录下请求的内容 logger.info("url:"+request.getRequestURL().toString()); logger.info("http method:"+request.getMethod()); logger.info("ip:"+request.getRemoteAddr()); } @AfterReturning(returning = "ret", pointcut = "webLog()") public void doAfterReturning(Object ret)throws Throwable{ logger.info("Response:"+ret); } }
-
启动访问localhost:8080/aop/index,控制台信息: