在使用通用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();
}
}