Search code examples
javaspringspring-mvcspring-annotations

Is it possible to nest controllers/have controllers as inner classes in Spring 4 MVC?


I want to have a controller that maps to /site/ and within that two different controllers to look something like:

@Controller
@RequestMapping(value="/api")
public class ApiController {
    @Controller
    @RequestMapping(value="/foo")
    public class FooController {
        //Some /foo/* methods here
    }

    @Controller
    @RequestMapping(value="/bar")
    public class BarController {
       //Some /bar/* methods here
    }

    //Other methods that don't match /foo or /bar
}

Is this okay or would be it be better practice to split it up into two separate controllers with /site/foo and /site/bar mappings?


Solution

  • Tying your class hierarchy to your resource hierarchy should not be the main design driver here.

    IN Spring MVC, Controllers are simple POJOs to make them easy to test, composition is favored over inheritance, annotations are used to convey meaning and make your code more readable.

    Nesting Controllers under Controllers defeats several of those goals.