1、新建一个自定义注解类
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD}) //表示写在方法上的注解
public @interface ZjxLog {
}
2、@Pointcut定义切点(表示遇到自己设置的注解时先执行@Before下的方法,等方法全部运行完后再运行@After下的方法)
@Component
@Aspect
@Slf4j
public class ZjxLogAspect {
@Pointcut("@annotation(com.yd.textspringboot.Aop.ZjxLog)")
public void ZjxLogAspect() {}
@Before("ZjxLogAspect()")
public void beforeZjxLog(JoinPoint joinPoint){
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
String methodName = joinPoint.getSignature().getName();
System.out.println("=========================== Method" + methodName + "() begin ===========================");
//执行时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = new Date();
String time = sdf.format(d);
System.out.println("Time : " + time);
//打印请求 URL
System.out.println("URL : "+ request.getRequestURL());
//打印 请求方法
System.out.println("HTTP Method : "+ request.getMethod());
//打印controller 的全路径以及执行方法
System.out.println("class Method : "+ joinPoint.getSignature().getDeclaringTypeName()+ "." + ((MethodSignature) joinPoint.getSignature()).getName());
//打印请求的 ip
System.out.println("IP : "+ request.getRemoteHost());
//打印请求入参
System.out.println("Request Args : "+ JSON.toJSONString(joinPoint.getArgs()));
System.out.println("==========================================================================");
}
@After("ZjxLogAspect()")
public void afterZjxLog(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
log.info("========================== Method" + methodName + "() end ======================================");
}
}
3、最后再Controller下的方法上写上自定义注解(表示运行该方法之前会先运行上面代码的@before代码,再执行该方法,最后执行上面代码的@After的代码)
@RestController
public class textController {
@GetMapping("text")
@ZjxLog
public ResultModel text(@RequestBody RequestModel requestModel){
ResultModel resultModel = new ResultModel();
resultModel.setMessage(requestModel.toString());
return resultModel;
}
}