SpringBoot自定义注解实现日志记录
业务描述:需要记录系统中谁操作了那个方法,参数是什么,做个简单的日志查看。需要添加依赖,然后写注解类,配置切面,在启动类启用即可。下面是具体步骤:
1.添加依赖,主要是加这2个依赖,日志等依赖根据实际情况添加
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> |
@Documented @Target({ElementType.METHOD,ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface Ulog { String msg() default "No Msg";//操作标识,用来表明这个方法是做什么的,会保存在日志里 } |
@Aspect
@Component
public class UlogAspect {
//这里是Ulog注解的路径,注意此方法不能有返回值
@Pointcut("@annotation(com.redies.demo.log.Ulog)")
public void annotationPointCut() {
}@Before("annotationPointCut()")
public void before(JoinPoint joinPoint) throws UnsupportedEncodingException {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();joinPoint.proceed();//让目标方法执行,具体见下面解释
MethodSignature sign = (MethodSignature)joinPoint.getSignature();
Method method = sign.getMethod();
Ulog ulog=method.getAnnotation(Ulog.class);
System.out.println("方法名称:"+method.getName());
System.out.println("方法类型:"+request.getMethod());
System.out.println("业务标识:"+ulog.msg());
System.out.println("请求地址:"+request.getRequestURI()+"&"+(request.getQueryString()==null?"": URLDecoder.decode(request.getQueryString(), "UTF-8")));
}
} |
在启动类上加注解@EnableAspectJAutoProxy
另外:关于操作人,根据实际登录逻辑添加。环绕通知 ProceedingJoinPoint 执行proceed方法的作用是让目标方法执行,这也是环绕通知和前置、后置通知方法的一个最大区别。简单理解,环绕通知=前置+目标方法执行+后置通知,proceed方法就是用于启动目标方法执行的。