Runtime loading of Controllers for Spring MVC and dynamically mapping requests/URLs

北慕城南 提交于 2019-12-07 10:46:04

问题


We are starting a new project using Spring MVC, and we would like to move away from annotation-driven request/url mapping. We wish to implement the following use case:

Use Case A

  1. User enters a URL.
  2. The request mapping handler retrieves a list of mappings (e.g. from the DB), and based on this dynamic list of mappings, it calls the relevant controller.

This is because we want to be able to do the following as well:

Use Case B

  1. We want to load a new Controller (perhaps a new reports module) into the web app without having to redeploy or do a server restart.
  2. We will map this new Controller to a URL and persist it somewhere (most likely the DB).
  3. We would like the Controller to be registered in the Spring app context (managed by Spring).
  4. We would then like to use this new Controller in the request mapping.

We've taken an initial look at the different ways we can implement this, but we are unsure of the best architecture/method to go about this route. A couple of questions:

  1. For Use Case A, how do we implement this within the Spring MVC framework (or if it's possible)?
  2. For Use Case B, is there a good framework or way to be able to do dynamically loading and registering of this for web applications? We've taken a cursory look at OSGI but it seems to be advisable for use in non-web applications.

回答1:


For Use case A : Instead of DB you can keep the url mappings in a property file and then use property place holder to initialize beans using xml configuration on context up. This way remaining inside the spring framework, you can avoid annotations.

For Use Case B : Tomcat supports dynamic reloading of classes but that to of only non structural changes in class file. But this has memory leaks as well as it doesnt cleans up old instance of class loader rather it creates a new instance.




回答2:


Its quite achievable using spring-mvc-router API.

Please check below link url-action mapping & routing in Spring MVC 3.0

Here the URL can be configured to controller.method using .conf file, but this can be achievable using java configuration, and i haven't tried so far.

Also if xml configuration chosen, then check out the property 'autoReloadEnabled', but its not adviceable for production use.

Hope this helps!!!



来源:https://stackoverflow.com/questions/19920912/runtime-loading-of-controllers-for-spring-mvc-and-dynamically-mapping-requests-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!