pom.xml中导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
新建 Package:aspect 包内建类:HttpAspect
通过注释:Aspect和Component来建立拦截类
@Aspect
@Component
public class HttpAspect {
@Before("execution(public * com.imooc.Controller.GirlController.*(..))")//拦截GirlController类下所有的方法 ..代表任意参数
public void log(){
System.out.println("拦截到了!");
}
执行顺序是先执行切面程序,再执行源程序
将切面整理为
@Aspect
@Component
public class HttpAspect {
@Pointcut("execution(public * com.imooc.Controller.GirlController.girlList(..))")
public void log(){}//定义一个共用方法,使用Pointcut注解
@Before("log()")
public void doBefore(){
}
@After("log()")
public void doAfter(){
}
}
抛弃prienln(),我们使用log日志来记录运行信息
@Aspect
@Component
public class HttpAspect {
private final static Logger logger
= LoggerFactory.getLogger(HttpAspect.class);
···
···
public void doAfter(){
logger.info("22222");
}
}
我们要通过Before来获取请求信息了
public void doBefore(JoinPoint joinPoint){
ServletRequestAttributes attrubutes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attrubutes.getRequest();
//url
logger.info("url={}",request.getRequestURI());
//method
logger.info("method={}",request.getMethod());
//ip
logger.info("ip={}",request.getRemoteAddr());
//类方法
logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()
+ "."+joinPoint.getSignature().getName());
//参数
logger.info("args={}",joinPoint.getArgs());
}
那我们如何获取返回给端的信息呢
@AfterReturning(returning = "object",pointcut = "log()")//用来返回信息
public void doAfterReturning(Object object){
logger.info("response={}",object.toString());
}
我们要在模板类里添加一个toString()的方法,类似这样
public String toString() {
return "Gril{" +
"id=" + id +
", cupSize='" + cupSize + '\'' +
", age=" + age +
'}';
}
才能返回object对象的数据