As I understand it, there are two main benefits to annotated controllers in Spring:
This seems to bring two main disadvantages, however:
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.
Let me argue with the disadvantages:
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.
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.
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
/HttpServletResponse
s.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With