I\'ve been using Spring MVC for three months now. I was considering a good way to dynamically add RequestMapping. This comes from the necessity to put controller parts in a
Please look at my solution. It doesn't create dynamic @RequestMapping in your code, but provides a HandlerMapping and Controller that handles all request. If you run that application, you will get hello world message in json.
Application class:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public MyCustomHandler myCustomHandler(MyCustomController myCustomController) {
MyCustomHandler myCustomHandler = new MyCustomHandler(myCustomController);
myCustomHandler.setOrder(Ordered.HIGHEST_PRECEDENCE);
return myCustomHandler;
}
}
MyCustomController
@Component
public class MyCustomController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
response.getWriter().println("{\"hello\":\"world\"}");
return null;
}
}
MyCustomHandler
public class MyCustomHandler extends AbstractHandlerMapping {
private MyCustomController myCustomController;
public MyCustomHandler(MyCustomController myCustomController) {
this.myCustomController = myCustomController;
}
@Override
protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
return myCustomController;
}
}
https://github.com/nowszy94/spring-mvc-dynamic-controller