笔记:我就是自己平时记下一些项目中用到的,有不对的地方大家可以指正。
pom文件要导入依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
在controller同级目录下创建一个文件夹aspect
package com.longfor.budget.aspect; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; 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 javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * 请求日志切面 * * * * @author jerry */ @Slf4j @Aspect//切面注解 @Component//构成 public class LogAspect { //设置切面的范围,具体想切入哪一个方法或者类名,可以百度 @Pointcut("execution(public * com.longfor.budget.controller..*.*(..))") public void doPointCut() { } //在类的执行之前,执行doPointCut @Before("doPointCut()") public void doBefore(JoinPoint joinPoint) throws Exception { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (Objects.nonNull(attributes)) { HttpServletRequest request = attributes.getRequest(); //可以获取到请求的参数 String args = (joinPoint.getArgs().length == 0) ? "" : new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL).writeValueAsString(joinPoint.getArgs()[0]); Map<String, Object> requestMap = new HashMap<>(); requestMap.put("httpUrl", request.getRequestURI()); requestMap.put("httpMethod", request.getMethod()); requestMap.put("ip", request.getRemoteAddr()); requestMap.put("classMethod", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); // requestMap.put("args", args); log.info("=========「请求」:{}", JSONObject.parseObject(JSON.toJSONString(requestMap))); } } //在类的执行之后在执行另一个方法(这个方法我这里没有,需要的话自己新建) @After("doPointCutAfter()") public void afterlogin(){System.out.println("after");} }