继承controller 引起的Ambiguous mapping.问题解决

在使用通用controller,有时需要重写对应mapping的方法,如果重写的方法参数不一样,但RequestMapping一样就会引起java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'xxx' method 异常。

解决办法: 重写RequestMappingHandlerMapping的getMappingForMethod方法。即子类controller已经有了相应的mapping,父类通用controller对应的mapping方法就不加入RequestMapping了,也就是getMappingForMethod返回null.

代码实现:

public class PathTweakingRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        RequestMappingInfo methodMapping = super.getMappingForMethod(method, handlerType);
        if (methodMapping == null)
            return null;
        if (method.getDeclaringClass() == handlerType) {
            return methodMapping;
        }
        RequestMapping declaredAnnotation = method.getDeclaredAnnotation(RequestMapping.class);
        Method[] declaredMethods = handlerType.getDeclaredMethods();
        RequestMapping requestMapping;
        for (Method declaredMethod : declaredMethods) {
            requestMapping = declaredMethod.getDeclaredAnnotation(RequestMapping.class);
            if (requestMapping != null && declaredAnnotation.value().equals(requestMapping.value())
                    && declaredAnnotation.method()[0].equals(requestMapping.method()[0])) {
                return null;
            }
        }
        return methodMapping;
    }
}
 @Configuration
 class WebMvcRegistrationsConfig  implements WebMvcRegistrations {
        @Override
        public PathTweakingRequestMappingHandlerMapping getRequestMappingHandlerMapping() {
            return new PathTweakingRequestMappingHandlerMapping();
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容