一、创建一个注解接口类
package com. common. annotation;
import java. lang. annotation. ElementType;
import java. lang. annotation. Retention;
import java. lang. annotation. RetentionPolicy;
import java. lang. annotation. Target;
@Target ( ElementType. METHOD )
@Retention ( RetentionPolicy. RUNTIME )
public @interface LogAnnotation {
String value ( ) default "" ;
}
二、创建一个切面类,切入点为注解接口
@Component
@Aspect
public class LogAspect {
@Pointcut ( "@annotation(com.common.annotation.LogAnnotation)" )
public void poinCut ( ) {
}
@Around ( "poinCut()" )
public Object around ( ProceedingJoinPoint joinPoint) throws Throwable {
long beginTime = System. currentTimeMillis ( ) ;
Object result = joinPoint. proceed ( ) ;
long time = System. currentTimeMillis ( ) - beginTime;
saveLog ( joinPoint, time) ;
return result;
}
private void saveLog ( ProceedingJoinPoint joinPoint, long time ) {
MethodSignature signature = ( MethodSignature) joinPoint. getSignature ( ) ;
Method method = signature. getMethod ( ) ;
SysLog sysLog = new SysLog ( ) ;
LogAnnotation logAnnotation = method. getAnnotation ( LogAnnotation . class) ;
if ( logAnnotation != null ) {
String description = logAnnotation . value ( ) ;
}
String className = joinPoint. getTarget ( ) . getClass ( ) . getName ( ) ;
String methodName = signature. getName ( ) ;
Object[ ] args = joinPoint. getArgs ( ) ;
try {
String params = JSONUtils. beanToJson ( args[ 0 ] ) . substring ( 0 , 500 ) ;
} catch ( Exception e) {
}
HttpServletRequest request = ( ( ServletRequestAttributes) RequestContextHolder. getRequestAttributes ( ) ) . getRequest ( ) ;
}
}
三、使用注解
@LogAnnotation ( "注解上的描述" )
@PostMapping ( "/userListController" )
public Result userListController ( @RequestParam User user ) {
Result result = new Result ( ) ;
return result ;
}