I have two Controllers:
@Controller
@Order(Ordered.LOWEST_PRECEDENCE)
public class BaseController {
@RequestMapping("/hello.html")
public String hello(ModelMap model) {
model.addAttribute("hello", "world");
return "hello";
}
}
@Controller
public class ProjectSpecificController {
@Autowired
private BaseController baseController;
@Override
@RequestMapping("/hello.html")
public String hello(ModelMap model) {
model.addAttribute("project", "name");
return baseController.hello(model);
}
}
As Spring would trigger this Exception: java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'baseController' bean method public java.lang.String com.example.BaseController.hello(org.springframework.ui.ModelMap) to {[/hello.html],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'projectSpecificController' bean method public java.lang.String com.example.ProjectSpecificController.hello(org.springframework.ui.ModelMap) mapped.
I would like to use the @Order
annotation to map ProjectSpecificController.hello
first and if there's already a mapping found for /hello.html
ignore the other mappings and do not register their methods:
public class OrderedRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
@Override
protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {
try {
super.registerHandlerMethod(handler, method, mapping);
} catch (IllegalStateException e) {
// mapping already happened for a controller of higher precedence, so ignore
}
}
}
Is it enough to catch the exception or do I have to look for the @Order
annotation myself? If I have to take care of the @Order
annotation myself: What's the best practice to realize my plan?