javaspringspring-mvc

Spring programmatically register RequestMapping


I have a working url as this: localhost/info

@Controller
@RequestMapping("/info")
public class VersionController {

   @RequestMapping(value = "", method = RequestMethod.GET)
   public @ResponseBody
   Map get() {
      loadProperties();
      Map<String, String> m = new HashMap<String, String>();
      m.put("buildTimestamp", properties.getProperty("Application-Build-Timestamp"));
      m.put("version", properties.getProperty("Application-Version"));
      return m;
   }

}

and I would to register some other mappings at initializing of my application as this:

localhost/xxxx/info
localhost/yyyy/info
localhost/zzzz/info

All these urls will return same response as localhost/info

The xxxx, yyyy part of the application is changeable. I have to register custom mappings as

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("???").setViewName("???");
}

Bu this is only working for views.

Any idea for dynamic registration?


Solution

  • You can register a new HandlerMapping where you can add the handlers for your URL paths; the most convenient implementation would be SimpleUrlHandlerMapping.

    If you want those handlers to be bean methods (like those annotated with @RequestMapping) you should define them as HandlerMethod wrappers so that the already registered RequestMappingHandlerAdapter will invoke them.