Given a \"standard\" spring boot application with a @RestController
, eg
@RestController
@RequestMapping(value = \"foo\", produces = \"applicatio
In some case, the @ConditionalOnXXX cannot work, for example, depends on another bean instance to check condition. (XXXCondition class cannot invoke a bean).
In such case, register controller in Java configuration file.
See source code(Spring webmvc 5.1.6):
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.isHandler(Class)
@Override
protected boolean isHandler(Class> beanType) {
return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
}
Should add @RequestMapping annotation on type level for the controller bean. See:
@RequestMapping // Make Spring treat the bean as request hanlder
public class MyControllerA {
@RequestMapping(path = { "/path1" })
public .. restMethod1(...) {
........
}
}
@RequestMapping // Make Spring treat the bean as request hanlder
public class MyControllerB {
@RequestMapping(path = { "/path1" })
public .. restMethod1(...) {
........
}
}
@Configuration
public class ControllerConfiguration {
/**
*
* Programmingly register Controller based on certain condition.
*
*/
@Bean
public IMyController myController() {
IMyController controller;
if (conditionA) {
cntroller = new MyControllerA();
} else {
controller = new MyControllerB();
}
return controller;
}
}