springboot 自定义注解_SpringBoot自定义注解实现日志记录功能

业务描述:需要记录系统中谁操作了那个方法,参数是什么,做个简单的日志查看。需要先添加依赖,然后写注解类,配置切面,在启动类启用即可。下面是具体步骤:

如果你喜欢SpringBoot的干货,可以关注我,这都是我工作中用到的技术,我会继续分享的。也欢迎去我个人技术博客,有其他技术资料:https://www.vsalw.com

67bc5b1025c9608b32a537473f8d01fb.png

1.添加依赖,主要是加这2个依赖,日志等依赖根据实际情况添加

org.springframework.boot

spring-boot-starter-aop

org.springframework.boot

spring-boot-starter-web

2.编写注解类Ulog

@Documented

@Target({ElementType.METHOD,ElementType.PARAMETER})

@Retention(RetentionPolicy.RUNTIME)

public @interface Ulog {

String msg() default “No Msg”;//操作标识,用来表明这个方法是做什么的,会保存在日志里

}

3.编写切面来拦截日志

@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”)));

}

}

4.启用对切面的支持

在启动类上加注解@EnableAspectJAutoProxy

另外:关于操作人,根据实际登录逻辑添加。环绕通知 ProceedingJoinPoint 执行proceed方法的作用是让目标方法执行,这也是环绕通知和前置、后置通知方法的一个最大区别。简单理解,环绕通知=前置+目标方法执行+后置通知,proceed方法就是用于启动目标方法执行的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值