I am using Spring’s MVC framework for an application I’m hosting on Google’s App Engine. So far, my controllers are registered via the @Controller annotation; however, prior to getting into Spring, I evaluated ASP.net MVC 2 which requires no configuration and is based on convention. Is convention over configuration (COC) the current and preferred method in the Java community to implement MVC with Spring? Also, this may be a result of my limited knowledge so far, but I noticed that I could only instantiate my Controllers the required constructor injection if I use the COC method via the ControllerClassNameHandlerMapping. For instance, the following controller bean config will fail if I use the DefaultAnnotationHandlerMapping.
<bean id="c" class="com.domain.TestController">
<constructor-arg ref="service" />
</bean>
<bean id="service" class="com.domain.Service" />
My com.domain.TestController controller works fine if I use ControllerClassNameHandlerMapping/COC but it results in an error when I use DefaultAnnotationHandlerMapping/Annotations.
To clarify, I can get the constructor injection to work if I add the @Autwired annotation to the constructor, but if I do, I have to remove the @RequestMapping annotation or I will get an error stating that the controller is being mapped to the URL more than once. Some researching online indicates that the ControllerClassNameHandlerMapping is loading and mapping my controller to the URL even though I have
<context:annotation-config /> and <context:component-scan base-package ... /> in my config file.
Honestly, I can overcome these issues. I really just want to know which method, annotation or COC, is the better investment.
Tricky question; it’s a little subjective and really just up to your personal preference or your dev team’s consensus. I personally like annotations because I feel like it’s more flexible. If you have to follow conventions to get your framework to “automagically” do stuff, you are stuck with whatever convention the framework developers decided on (granted, it’s usually not a bad convention, but you are stuck with it). During my time of using Spring (2 years or so), it’s always seemed like our team has started out using COC, only to realize later that our needs aren’t really best served by the typical convention.
I also feel like annotations improve the readability of your code. When looking at an annotated class, I can understand what it does and how it does it without needing to reference the application context.
As for your second question (injecting beans into a controller), here’s some code to show how I usually wire a controller.
web-servlet.xml
TestController.java
TestDAO would then have this class declaration:
I usually don’t use constructor wiring because this is usually simpler, but if you need constructor wiring, I can post an example of that instead.