Springboot使用自定义注解实现系统日志处理
在日常项目开发中,系统的日志处理是必不可少的,最近因项目需要,在项目中添加了系统处理日志。
文章来源:https://blog.****.net/qq_23167527/article/details/78623163
1、主要原理还是利用AOP的原理,因此需要在项目中定义一个切面类,需要使用到@Aspect注解,在pom.xml中添加jar包:spring-boot-starter-aop
2、书写自定义注解,可以更具自己的需求来写
在自定义注解中,长会使用到以下三个注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
作用就不在说明,自定查阅资料
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 SystemServicesLog {
String value();
}
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 SystemControllerLog {
String value();
}
3、切面类的实现
import com.mp.web.annotation.SystemControllerLog;
import com.mp.web.annotation.SystemServicesLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
/**配置日志切面类,@Aspect把当前类标识为一个切面类工容器读取*/
@Aspect
@Component
public class MpLogAop {
/**
* 使用后置通知,并配置切入点表达式,联合自定义控制层日志注解,记录日志
* @param joinPoint
* @param systemControllerLog
*/
@After("execution(* com.mp.web.controller.*.*(..)) && @annotation(systemControllerLog)")
public void afterControllerLog(JoinPoint joinPoint,SystemControllerLog systemControllerLog){
String logValue = systemControllerLog.value();
System.out.println("后置通知开始执行==》控制层日志log==》用户执行了【"+logValue+"】操作");
}
/**
* 使用后置通知以及自定义服务层日志注解,记录服务层操作日志
* @param joinPoint
* @param systemServicesLog
*/
@After("execution(* com.mp.web.services.*.*(..)) && @annotation(systemServicesLog)")
public void afterServiceLog(JoinPoint joinPoint,SystemServicesLog systemServicesLog){
String logValue = systemServicesLog.value();
System.out.println("后置通知开始执行==》服务层日志log==》用户执行了【"+logValue+"】操作");
}
}
注意,以下红色框中的名称需要相同
4、准备工作做好后,就可以使用自定义的注解添加在服务层或者控制层的方法上
5、运行项目,打印日志
可以看到自定义注解以及切面类已经实现。
在别处看到这种方法,一次文章来作为自己的笔记,写的不好,欢迎拍砖。