Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Spring annotated controllers preferable to traditional mappings?

As I understand it, there are two main benefits to annotated controllers in Spring:

  1. Elimination of the need to extend a base class / implement an interface.
  2. Elimination of Yet Another configuration file.

This seems to bring two main disadvantages, however:

  1. The coupling between the framework and the controller would seem to be tighter with the use of annotations, compared to using class extension / implementation.
  2. A single file containing mappings seems easier to maintain, rather than digging through code in multiple files looking for an annotation.

Although I personally consider the aforementioned disadvantages to outweigh the benefits, the use of annotations seems to be preferred. This brings me to the question: why are Spring annotated controllers preferable to traditional mappings?

Edit with regards to coupling:

I realise that in both situations there is some coupling with the underlying framework involved. The Controller interface required by Spring consists of a single method, and could be mostly abstracted away (eg. interface MyController extends SpringController). Annotations on the other hand, apart from being framework specific, require a whole bunch of imports in every single file.

like image 461
etheros Avatar asked Jan 05 '11 17:01

etheros


2 Answers

Let me argue with the disadvantages:

  1. It doesn't. This is metadata that can easily go away without affecting functionality. On the other hand having to extend certain classes, and use their methods makes it impossible to get rid of the framework later.

  2. It's the same. I've used both approaches, and neither is bad. With modern IDE search capabilities, and with proper naming conventions, not having a single configuration file is just as easy.

like image 146
Bozho Avatar answered Sep 21 '22 17:09

Bozho


There are several additional advantages:

  • Logical grouping of several actions in a single controller class (though it's also possible with MultiActionController, but not so flexible)

  • Simplification of unit testing, since in most cases you can pass simple arguments and don't need to prepare mock HttpServletRequest/HttpServletResponses.

  • Additional flexibility of mapping with @RequestParam, @PathVariable, etc (though it could be implemented in traditional controllers, but I think not so elegant as with annotations due to static nature of traditional controllers).

Also I can't agree with the first disadvantage - in my opinion annotations introduce much less coupling than inheritance. For example, you can even use compiled annotated controller as a regular class without having Spring in the classpath (though compilation of annotated source code still requires annotations in the build path).

like image 26
axtavt Avatar answered Sep 19 '22 17:09

axtavt