1.定义一个自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author lin
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogExecution {
String value() default "";
}
2.定义一个aop
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
/**
* @author lin
*/
@Aspect
@Component
@Slf4j
public class LogExecutionAspect {
@Around("@annotation(LogExecution)")
public Object logExecution(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
LogExecution logExecution = signature.getMethod().getAnnotation(LogExecution.class);
String logMessage = logExecution.value();
String methodName = signature.getName();
Object[] args = joinPoint.getArgs();
log.info("Method [{}] - {}- 入参: {} ", methodName, logMessage,JSON.toJSONString(args));
Object result = joinPoint.proceed();
log.info("Method [{}] - {}- 出参: {} ", methodName, logMessage,JSON.toJSONString(result));
return result;
}
}
3.运用到请求代码中
/**
* @author lin
*/
@RestController
public class SampleController {
@GetMapping("/sample")
@LogExecution("This is a sample method")
public String sampleMethod(@RequestParam String param) {
return "Hello, " + param;
}
@GetMapping("/anotherSample")
@LogExecution("获取用户接口")
public String anotherSampleMethod(@RequestParam String param) {
return "Hi, " + param;
}
}
效果