Saturday, 1 September 2012

Annotation based Configuration in spring

This is 13 of 13 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

Part-1:Introduction to spring framework
Part-2:Dependency injection(ioc) in spring
Part-3:Spring hello world example in eclipse
Part-4:Dependency injection via setter method in spring
Part-5:Dependency injection via constructor in spring
Part-6:Spring Bean scopes with examples
Part-7:Initializing collections in spring
Part-8:Beans Autowiring in spring 
Part-9:Inheritance in Spring 
Part-10:Spring ApplicationContext 
Part-11:Spring lifetime callbacks 
Part-12:BeanPostProcessors in Spring 
Part-13:Annotation based Configuration in spring 

There are two ways via which you can inject dependency in spring
  1. By configuring XML.
  2. By using annotation.
In all our previous posts,we have injected dependency by configuring XML file but instead of doing this,we can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

You might think what if you have done both i.e.used annotations and XML both.In that case,XML configuration will override annotations because XML configuration will be injected after annotations.

Now annotations based configuration is turned off by default so you have to turn it on by entering <context:annotation-config/> into spring XML file.

ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 <context:annotation-config/>
 <!-- beans declaration goes here -->
</beans>

Now you are ready to use annotations in your code.Let us discuss few important annotations in spring

@Required:

 The @Required annotation applies to bean property setter methods.

@Autowired:

The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties.

 @Qualifier:

The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.

 JSR 250 Annotations: 

Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations.