使用自定义注解配合切面打日志
下面内容作为demo演示
编写自定义注解:
@Target ( ElementType . METHOD )
@Inherited
@Documented
@Retention ( RetentionPolicy . RUNTIME )
public @interface SystemLog {
String value ( ) default "" ;
String type ( ) default "" ;
Class target ( ) ;
}
为controller层加持上注解:
@GetMapping ( "/query" )
@SystemLog ( value = "test" , type = "query" , target = Student . class )
public String listStudents ( ) {
List < Student > all = studentService. findAll ( ) ;
return JSON . toJSONString ( all) ;
}
定义MyAspect类用于执行切面操作:
@Aspect
@Slf4j
@Component
public class MyAspect {
@Pointcut ( "@annotation(com.example.mybatispluslearn.annotation.SystemLog)" )
private void myPointcut ( ) { }
@Around ( value= "myPointcut()" )
public Object around ( ProceedingJoinPoint joinPoint) throws Throwable {
Object proceed = joinPoint. proceed ( ) ;
MethodSignature signature = ( MethodSignature ) joinPoint. getSignature ( ) ;
Method method = signature. getMethod ( ) ;
SystemLog annotation = method. getAnnotation ( SystemLog . class ) ;
String type = annotation. type ( ) ;
Class target = annotation. target ( ) ;
String value = annotation. value ( ) ;
log. info ( "执行切面日志操作。。。type:{} target:{} value:{}" , type, target. getSimpleName ( ) , value) ;
return proceed;
}
}
以上内容就是通过自定义注解以及面向切面编程实现的日志记录的demo