You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3中自定义注解如何获取@RequestMapping与@PutMapping的值?

自定义@ToTake注解获取Spring MVC注解值的实现方法

当然可以实现,用Spring AOP就能搞定这个需求,具体步骤如下:

  • 先定义@ToTake注解,设置运行时可见且作用在方法上:

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ToTake {
    }
    
  • 编写AOP切面类,通过JoinPoint拿到目标方法和类的注解信息:

    @Aspect
    @Component
    public class ToTakeAspect {
    
        @Before("@annotation(com.yourpackage.ToTake)")
        public void processToTake(JoinPoint joinPoint) {
            // 获取目标方法签名
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method targetMethod = signature.getMethod();
    
            // 提取方法上的@PutMapping注解值
            PutMapping putMappingAnno = targetMethod.getAnnotation(PutMapping.class);
            if (putMappingAnno != null) {
                String[] methodPaths = putMappingAnno.value();
                System.out.println("方法级路径:" + Arrays.toString(methodPaths));
            }
    
            // 提取类上的@RequestMapping注解值
            Class<?> controllerClass = joinPoint.getTarget().getClass();
            RequestMapping classRequestMappingAnno = controllerClass.getAnnotation(RequestMapping.class);
            if (classRequestMappingAnno != null) {
                String[] classPaths = classRequestMappingAnno.value();
                System.out.println("类级路径:" + Arrays.toString(classPaths));
            }
        }
    }
    
  • 测试验证:当调用PUT /queries/{id}接口时,切面会自动打印类和方法的路径信息,将两者拼接就是完整的接口路径/queries/{id}。

如果需要处理更复杂的场景(比如识别@RequestMapping的派生注解、处理继承的注解),可以改用AnnotationUtils.findAnnotation方法获取注解,它能更灵活地处理各种注解继承和派生情况。

内容的提问来源于stack exchange,提问作者robert trudel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 05:12:10