AOP 不局限于SpringBoot,这只是AOP在SpringBoot下应用。
1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.添加 AOP
package com.example.utils;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import lombok.extern.slf4j.Slf4j;
@Aspect //
@Component //
@Slf4j
public class HttpAspect {
/***
* 进入方法之前拦截
*/
@Before("common()")
public void toBefore() {
log.info("进入方法之前拦截");
}
/***
* 进入方法之后拦截
*/
@After("common()")
public void doAfter(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 获取url
log.info("url = {}", request.getRequestURI());
// 获取method
log.info("method = {}", request.getMethod());
// 获取ip
log.info("ip = {}", request.getRemoteAddr());
// 获取类方法
log.info("class_method = {}", joinPoint.getSignature().getDeclaringTypeName());
// 获取参数
log.info("args = {}", joinPoint.getArgs());
log.info("-----------------");
log.info("进入方法之后拦截");
}
/***
* 共通
*/
@Pointcut("execution(public * com.example.controller.WelcomeController.user(..))")
public void common() {
log.info("这是共通 aop");
}
/***
* 返回的信息值
* @param object
*/
@AfterReturning(returning="object", pointcut="common()")
public void doAfterReturning(Object object) {
log.info("response:"+object);
}
}