自定义注解实现

实际开发中,可能会用到自定义注解,以下为demo

主要步骤:1、自定义注解对象;2、借助AOP

1、添加AOP依赖:

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

2、定义注解

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

3、AOP的around的环绕通知

@Aspect
@Component
public class AnnitationConfig {


    // 拦截带有 @RequestAnnotation 注解的方法
    @Around("@annotation(com.es.esdemo.demo.MyAnnotation)")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取注解
        MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
        String value = annotation.value();
        int count = annotation.count();

        // 在接口请求前执行逻辑
        System.out.println("value:" + value);
        System.out.println("count:" + count);

        // 执行目标方法
        Object result = joinPoint.proceed();

        // 在接口请求后执行逻辑
        System.out.println("After request, result: " + result);

    }
}

以上当拿到value和count两个值后,可以自行进行业务操作

测试代码:

controller层

    @GetMapping("/getAnnotation")
    public String getAnnotation(){
        return demo1Service.myMethod();
    }

serviceImpl层

    @Override
    @MyAnnotation(value = "service的方法", count = 33)
    public String myMethod() {
        return "返回结果";
    }

控制台打印如下:

value:service的方法
count:33
After request, result: 返回结果

 

posted @ 2025-03-14 22:27  多多指教~  阅读(46)  评论(0)    收藏  举报