javaspring-mvcnaming-conventionsconvention-over-configur

Package-based controller resolving in Spring MVC


I would like to know if it is possible to make Spring MVC work like Stripes when resolving controller classes.

Normally I can annotate a controller with a @RequestMapping in order to map it to its URL.

However my boss asked for a convention-over-configuration mechanism derived from Stripes, which we are progressively abandoning after years of employment.

You see, Stripes Actions are scanned in classpath under packages that contain stripes.action in their name. Each subpackage is a virtual directory and ultimately a class named SomethingAction will map to url Something.action.

Whan I need to do is as follows:

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

Basically I'd like to make Spring MVC automagically map controllers according to their full class name instead of using @RequestMapping on every controller.

Important! I don't need exactly that naming convention (web.controllers) if Spring MVC has already a naming convention. I simply need one.

I have found no clue so far. Thanks


Solution

  • ControllerClassNameHandlerMapping does it out-of-box what you are looking forward to.

    Simply set the base package as com.example.product.web.controllers and the sub-packages would be mapped as path for you. To quote from API docs

    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".

    Do note that it is constrained to have only single base package. Incase there are different package hierarchies to scan, the behaviour of ControllerClassNameHandlerMapping has to be customized accordingly.