基于springboot环境的自定义注解

一、说明
基于springboot,实现自定义注解。
可做日志记录,方法增强等等。

二、依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

注意:如果使用的不是spring-boot-starter-parent管理依赖版本,需要引入version版本号。

三、注解类

package com.demo.annotation.anno;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface LogActive {

    String name();

    String info();

}

四、切面类
注意两个注解:@Aspect 和 @Component

package com.demo.annotation.aspect;

import com.demo.annotation.anno.LogActive;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;

import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogActiveAspect {

    @Pointcut(value = "@annotation(logActive)")
    public void logActivePointcut(LogActive logActive) {
    }


    @Around(value = "logActivePointcut(logActive)")
    public void around(ProceedingJoinPoint joinPoint, LogActive logActive) {
        try {
            System.out.println("方法执行前============");
            System.out.println("注解参数name:" + logActive.name());
            System.out.println("注解参数info:" + logActive.info());
            joinPoint.proceed();
            System.out.println("方法执行后============");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
}

配置无误后,可以直接跳转到注解引用的位置,如下图:
在这里插入图片描述

五、测试
创建controller,暴露外界访问。使用postman测试。在访问方法上引用自定义注解。

package com.demo.annotation.controller;

import com.demo.annotation.anno.LogActive;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoTestController {

    @LogActive(name = "DemoTestController", info = "DemoTestController日志记录")
    @GetMapping("/test")
    public void test(String str) {
        System.out.println("controller 处理:" + str);
    }
}

六、输出结果
在这里插入图片描述
七、出不来,私信我。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值