Using inheritance in Spring MVC 3.1

Explore the use of inheritance in Spring MVC.

Is it good to have a basic controller that other controllers can extend?

The base controller will support common functionality for all controllers. For Eg, get the handle of the logged in user, etc.

If using a base controller is not a good idea, are there any other suggestions for implementing something like the one I mentioned above.

+3


source to share


1 answer


It is perfectly legal to have a base controller that other controllers can distribute. When Spring introduced the @Controller annotations, they paved the way for you to use whatever class hierarchy you want.

Just keep in mind that, as an object oriented design principle, it is useful to maintain composition over inheritance. As a general rule (not a hard and fast rule) I would recommend moving the generic controller code into a class whose interface can be injected into your controllers via @Inject or @Autowired .



Another suggestion for getting the logged in user handle is a bit more work, but very nice once you get it. See the discussion here about using the current user annotation in controller method arguments . This is what I am doing in my project and it works great!

+2


source







All Articles