3

Researching the use of inheritance in Spring MVC.

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

The base controller would be to hold functionality common to all controllers.For E-g getting a handle to the logged-in user etc.

If using the base controller is not a good idea are there any other suggestions to implement something like what I have mentioned above.

souser
  • 796
  • 2
  • 8
  • 25

1 Answers1

2

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

Just be aware that as an object oriented design principle, it's good to favor composition over inheritance. As a rule of thumb (not a hard and fast rule) I would recommend moving your common controller code into a class whose interface can be injected into your controllers via @Inject or @Autowired.

Another suggestion for getting a handle to the logged-in user is a little more work but very nice once you have it. See the discussion here about using a current user annotation on your controller method arguments. This is what I do on my project and it works great!

Community
  • 1
  • 1
Jason
  • 7,356
  • 4
  • 41
  • 48
  • Thank you for your inputs Jay.But if I did use composition with common code in one class I would still need to inject that in every controller.I will look at the links you shared.If you do think of any other ideas please do share. – souser Feb 17 '13 at 20:03
  • 1
    You have to consider your options and apply design principles to your own situation. If you have a lot of controllers maybe it makes more sense to use inheritance. – Jason Feb 18 '13 at 15:10
  • 1
    Another thought if you go the inheritance route is to keep the inherited method(s) non-final so that you can override it in unit tests (say, to return a mock user object instead of calling static security methods). This will ease unit testing without using dependency injection. – Jason Feb 18 '13 at 15:11