在使用通用controller曼月,有時(shí)需要重寫(xiě)對(duì)應(yīng)mapping的方法,如果重寫(xiě)的方法參數(shù)不一樣,但RequestMapping一樣就會(huì)引起java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'xxx' method 異常。
解決辦法: 重寫(xiě)RequestMappingHandlerMapping的getMappingForMethod方法。即子類(lèi)controller已經(jīng)有了相應(yīng)的mapping,父類(lèi)通用controller對(duì)應(yīng)的mapping方法就不加入RequestMapping了,也就是getMappingForMethod返回null.
代碼實(shí)現(xiàn):
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();
}
}