springBoot自定义注解实现AOP,进行方法入参日志打印

pom文件

<!--        自定义注解-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

注解编写

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String param() default "";
}

切面类

@Aspect
@Component
public class MyAop {
    private static final Logger logger = LoggerFactory.getLogger(MyAop.class);

    @Around("@annotation(MyAnnotation)")
    public Object method(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        Object[] args = pjp.getArgs();
        String argsStr = "";
        if (args.length > 0) {
            for (int i = 0; i < args.length; i++) {
                if (i == 0) {
                    argsStr += "***参数为:" + args[i];
                } else {
                    argsStr += "--&--" + args[i];
                }
            }
        }
        String s = signature.toString();
        logger.info(s+"===Start" + argsStr);
        try {
            return pjp.proceed();
        } finally {
           logger.info(s+"===End");
        }
    }
}

在需要的地方添加注解

我是在这个controller上添加注解,每次访问的时候就会打印日志。
/**
     * 测试redis
     */
    @RequestMapping("/redisTest1")
    @MyAnnotation
    public void redisest1(String key, String value) {
        redisUtil.addObject(key, value, 10000);
    }

日志格式如下

2019-12-12 11:42:30.615  INFO 6776 --- [nio-8080-exec-5] com.qinghua.bird.config.logConfig.MyAop  : void com.qinghua.bird.controller.CheckServer.redisest1(String,String)===Start***参数为:liqinghua--&--hahaha

2019-12-12 11:42:30.621  INFO 6776 --- [nio-8080-exec-5] com.qinghua.bird.config.logConfig.MyAop  : void com.qinghua.bird.controller.CheckServer.redisest1(String,String)===End
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

重生之我在异世界打工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值