With the advent of Spring 3 there has been an widespread use of annotations and annotations based configurations. It brings down the development time and also has it's own advantages & disadvantages.
However there are very few examples online which shows a complete Spring MVC application configured using ONLY bean based configuration. In most of the cases you will find atleast the dispatcher-servlet.xml lying around even in a Bean based configuration.
So, let's see how can we get rid of any Spring related XML files for configuration and develop a Spring MVC application. First let's take a look at the application's entry point and the only XML file of any standard web application web.xml:
Note that we have configured ContextLoaderListener to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext and added contextConfigLocation as the Beans Class which will contain the spring configuration.
Now, let's see the the Bean based configuration class:
You don't have to declare your bean in your context file in this bean based config, instead Annotate the class with @Component, @Service, @Controller or @Repository and our @ComponentScan annotation in BeansConfig.java will automatically register them in Spring context. Your Bean configuration class should be annotated with @Configuration annotation.
Make sure you mark Service classes with @Service annotation and not with @Component as the former is the more specialized annotation for Service components. Similarly, @Controller for Controller components and @Repository for DAO components in your application.
Note that we have configured ContextLoaderListener to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext and added contextConfigLocation as the Beans Class which will contain the spring configuration.
Now, let's see the the Bean based configuration class:
You don't have to declare your bean in your context file in this bean based config, instead Annotate the class with @Component, @Service, @Controller or @Repository and our @ComponentScan annotation in BeansConfig.java will automatically register them in Spring context. Your Bean configuration class should be annotated with @Configuration annotation.
Make sure you mark Service classes with @Service annotation and not with @Component as the former is the more specialized annotation for Service components. Similarly, @Controller for Controller components and @Repository for DAO components in your application.
The controller below shows also the use of @Autowired annotation for auto-wiring and injecting OfficeAddress into Employee bean.
Download the Eclipse project SpringDIAndAutowired.zip
Best article on Annotation based configuration in XML.
ReplyDelete