本文主要聊一下如何在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<RequestMappingInfo,HandlerMethod>

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<ContextRefreshedEvent>接口,在

@Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //.......
    }

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


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...