spring获取controller方法中自定义注解的信息

本文介绍如何在Spring MVC容器启动时获取带有特定自定义注解的方法信息。通过使用`RequestMappingHandlerMapping`类及其`getHandlerMethods`方法,结合反射技术判断方法上是否存在所需注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文主要聊一下如何在spring容器启动时,获取有自定义注解的方法信息。

RequestMappingHandlerMapping

spring-webmvc-4.3.10.RELEASE-sources.jar!/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java

public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMapping
        implements MatchableHandlerMapping, EmbeddedValueResolverAware {

    private boolean useSuffixPatternMatch = true;

    private boolean useRegisteredSuffixPatternMatch = false;

    private boolean useTrailingSlashMatch = true;

    private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();

    private StringValueResolver embeddedValueResolver;

    private RequestMappingInfo.BuilderConfiguration config = new RequestMappingInfo.BuilderConfiguration();

    //....
}复制代码
  • getHandlerMethods
    spring-webmvc-4.3.10.RELEASE-sources.jar!/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java
    /**
       * Return a (read-only) map with all mappings and HandlerMethod's.
       */
      public Map<T, HandlerMethod> getHandlerMethods() {
          this.mappingRegistry.acquireReadLock();
          try {
              return Collections.unmodifiableMap(this.mappingRegistry.getMappings());
          }
          finally {
              this.mappingRegistry.releaseReadLock();
          }
      }复制代码

    主要用到这个getHandlerMethods方法

Map

for(Map.Entry<RequestMappingInfo,HandlerMethod> entry : urlMethodMapping.entrySet()){

            RequestMappingInfo info = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();
            Method method = handlerMethod.getMethod();

            if(!method.isAnnotationPresent(DemoAnno.class)){
                continue;
            }

            DemoAnno demoAnno = method.getAnnotation(DemoAnno.class);
            //......
        }复制代码

通过这个HandlerMethod就可以获取具体的请求的方法,然后利用反射去判断是否有标注自己所需要的注解。

启动时处理

实现ApplicationListener接口,在

@Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //.......
    }复制代码

在onApplicationEvent中去处理
这样就大功告成了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值