基于包的控制器在 Spring MVC 中解析

Package-based controller resolving in Spring MVC

我想知道在解析控制器 classes 时是否可以使 Spring MVC 像 Stripes 一样工作。

通常我可以用 @RequestMapping 注释一个控制器,以便将它映射到它的 URL。

然而,我的老板要求从 Stripes 派生出一种约定优于配置的机制,经过多年的使用,我们逐渐放弃了这种机制。

你看,在名称中包含 stripes.action 的包下的 class 路径中扫描条纹 Actions。每个子包都是一个虚拟目录,最终一个名为 SomethingAction 的 class 将映射到 url Something.action.

我需要做的事情如下:

com.example.product.web.controllers.secure.admin.UserController 映射到 /secure/admin/user com.example.something.different.from.before.web.controllers.pub.WelcomeController mapping/pub/welcome

基本上我想让 Spring MVC 根据完整 class 名称自动映射控制器,而不是在每个控制器上使用 @RequestMapping

重要!我不需要完全那个命名约定(web.controllers)如果Spring MVC已经有一个命名约定。我只需要一个。

到目前为止我还没有找到任何线索。 谢谢

ControllerClassNameHandlerMapping 开箱即用,满足您的期待。

只需将基本包设置为com.example.product.web.controllers,子包将为您映射为路径。引用 API 文档

Specify a base package like "com.mycompany.myapp" to include subpackages within that base package as path elements, e.g. generating the path "/mymodule/buyform" for the class name "com.mycompany.myapp.mymodule.BuyForm".

Subpackage hierarchies are represented as individual path elements, e.g. "/mymodule/mysubmodule/buyform" for the class name "com.mycompany.myapp.mymodule.mysubmodule.BuyForm".

请注意,它被限制为只有一个 基础包 。如果有不同的包层次结构要扫描,ControllerClassNameHandlerMapping 的行为必须相应地定制。