我正在尝试为我的 Spring Boot Rest 项目实现继承的 Controller 。正如您在示例代码片段中看到的,我在 BaseTableController 上为所有 Controller 都有标准端点,但对于某些具体 Controller ,我需要重写方法。当我像这样实现它时,我得到 Ambiguous mapping. Cannot map 'clientRfmController' method
启动时出现异常。
public abstract class BaseTableController<T extends BaseTableModel> {
@Override
public BaseTableService<T> getService() {
return (BaseTableService<T>) super.getService();
}
@GetMapping({
PATH_GET,
PATH_VIEW_GET}
)
public T getWithParam(@RequestParam UUID gid) {
T t = null;
if (gid != null) {
t = getService().get(gid);
}
return getWithErrorCheck(t);
}
}
-
@RestController
@RequestMapping(TBL_CLIENTRFM)
public class ClientRfmController extends BaseTableController<ClientRfmCommon> {
@Override
public ClientRfmService getService() {
return (ClientRfmService) super.getService();
}
@GetMapping(value = {PATH_GET, PATH_VIEW_GET})
public List<ClientRfmCommon> getByAccid(Long accid, @RequestParam(required = false) UUID gid) {
List<ClientRfmCommon> byAccid = null;
if (gid != null) {
byAccid = Collections.singletonList(super.getWithParam(gid));
} else {
byAccid = Collections.singletonList(getService().getByAccid(accid));
}
return byAccid;
}
}
我通过实现自定义 RequestMappingHandlerMapping 找到了解决方法。
@Configuration
public class WebMvcRegistrationsConfig implements WebMvcRegistrations {
@Override
public OoRequestMappingHandlerMapping getRequestMappingHandlerMapping() {
OoRequestMappingHandlerMapping ooRequestMappingHandlerMapping = new OoRequestMappingHandlerMapping();
ooRequestMappingHandlerMapping.setOrder(0);
return ooRequestMappingHandlerMapping;
}
}
-
public class OoRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
@Override
protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {
HandlerMethod existingHandlerMethod = getHandlerMethods().get(mapping);
if (existingHandlerMethod != null) {
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
if (handlerMethod.getMethod().getDeclaringClass().isAssignableFrom(existingHandlerMethod.getMethod().getDeclaringClass())) {
logger.warn(handlerMethod.getBeanType().getSimpleName() + " type (" + handlerMethod.getMethod().getDeclaringClass().getSimpleName() + "->" + handlerMethod.getMethod().getName() +
") registration omitted to avoid ambigious mapping (" + existingHandlerMethod.getMethod().getDeclaringClass().getSimpleName() + "->" + existingHandlerMethod.getMethod().getName() + ")");
return;
}
unregisterMapping(mapping);
}
super.registerHandlerMethod(handler, method, mapping);
}
}
- 这是处理此问题的正确方法吗?
- 当我添加@EnableWebMvc注释时,这变得毫无用处。还有更通用的解决方案吗?
最佳答案
@GetMapping({
PATH_GET,
PATH_VIEW_GET}
)
在父类和子类中重复,因此您面临不明确的映射。请更改其中的路径。
关于java - Spring Boot RestController 继承和不明确的映射问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55138799/