Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Annotation Spring MVC <mvc:annotation-driven />

I'm very new to Spring MVC and I have one question for you.

I know that tag <mvc:annotation-driven /> handles the annotation such as @Controller, @RequestMapping in a servlet configuration, but I'm using portlets and I am very curious how this annotation works here?

Thx!

like image 401
Dina Bogdan Avatar asked Dec 04 '22 22:12

Dina Bogdan


2 Answers

It works the same.

If you go with java configuration you'll use:

...
@Configuration
@EnableWebMvc <- (equivalent to <mvc:annotation-driven />)
@ComponentScan(basePackageClasses = { MyConfiguration.class })
...

Or if you go with xml configuration you'll use:

...
<mvc:annotation-driven />
<context:component-scan base-package="package.*" />
...
like image 197
T. Jung Avatar answered Dec 11 '22 17:12

T. Jung


mvc:annotation-driven is used for enabling the Spring MVC components with its default configurations.

If you dont include mvc:annotation-driven also your MVC application would work if you have used the context:component-scan for creating the beans or defined the beans in your XML file

. But, mvc:annotation-driven does some extra job on configuring the special beans that would not have been configured if you are not using this element in your XML file.

This tag would registers the HandlerMapping and HandlerAdapter required to dispatch requests to your @Controllers. In addition, it also applies some defaults based on what is present in your classpath. Such defaults are:

  • Using the Spring 3 Type ConversionService as a simpler and more robust alternative to JavaBeans PropertyEditors
  • Support for formatting Number fields with @NumberFormat

  • Support for formatting Date, Calendar, and Joda Time fields with @DateTimeFormat, if Joda Time is on the classpath

  • Support for validating @Controller inputs with @Valid, if a JSR-303 Provider is on the classpath
  • Support for reading and writing XML, if JAXB is on the classpath
  • Support for reading and writing JSON, if Jackson is on the classpath

context:component-scan element in the spring configuration file would eliminate the need for declaring all the beans in the XML files. Look at the below declaration in your spring configuration file:

<context:component-scan base-package="org.controller"/>

The above declaration in the spring application configuration file would scan the classes inside the specified package and create the beans instance. Note that it could create beans only if that class is annotated with correct annotations. The following are the annotations scanned by this element:

  • @Component
  • @Repository
  • @Service
  • @Controller
like image 44
Vishal Roy Avatar answered Dec 11 '22 17:12

Vishal Roy