Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Sunday, September 2, 2012

@Autowired Annotation in spring

 The @Autowired annotation provides control over where and how autowiring can be done.This annotations can be done on setter method,contructor or property.We will see each in detail with example.

@Autowired on setter methods:

By default,whereever spring containers finds @autowire notation,it autowires bean byType. You can use @Autowire annotation on setter method to get rid of <property> tag in XML configuration file.

Example:

For configuring spring in your eclipse ide please refer hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Autowired;
public class Country {

String countryName;
Capital capital;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Capital getCapital() {
return capital;
}
@Autowired
public void setCapital(Capital capital) {
this.capital = capital;
}
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java

package org.arpit.javapostsforlearning;

public class Capital {

String capitalName;

public String getCapitalName() {
return capitalName;
}

public void setCapitalName(String capitalName) {
this.capitalName = capitalName;
}
}

3.AutowiredAnnotationInSpringMain.java

This class contains main function.Create AutowiredAnnotationInSpringMain.java under package org.arpit.javapostsforlearning.Copy following content into AutowiredAnnotationInSpringMain.java

 package org.arpit.javapostsforlearning;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AutowiredAnnotationInSpringMain{

public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

Country countryObj = (Country) appContext.getBean("CountryBean");
String countryName=countryObj.getCountryName();
Capital capital=countryObj.getCapital();
String capitalName=capital.getCapitalName();
System.out.println(capitalName+" is capital of "+countryName);

}
}

4.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/>
<bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
<property name="countryName" value="India" />
</bean>
<bean id="CaptialBean" class="org.arpit.javapostsforlearning.Capital">
<property name="capitalName" value="Delhi" />
</bean>
</beans>

As you can see there is no relationship between above two beans,but we have used @autowired annotation which will automatically wire above beans on the basis of type.

5.Run it:

When you will run above application,you will get following as output.

Delhi is capital of India

@Autowired on properties:

you can use @Autowired on property to get rid of setter method.Spring container automatically assign values to corresponding attributes.You don't need setter methods for that.Make following changes to above code:

Country.java:

package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Autowired;
public class Country {

String countryName;

@Autowired
Capital capital;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Capital getCapital() {
return capital;
}
}

Run it:

When you will run above application,you will get following as output.

Delhi is capital of India

@Autowired on Constructor:

you can use @autowired on constructor also and it will work even if you didn't define <constructor-arg> tag in XML configuration file.Make following changes to above code:

Country.java:

package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Autowired;
public class Country {

String countryName;
Capital capital;

@Autowired
public Country(String countryName, Capital capital) {
super();
this.countryName = countryName;
this.capital = capital;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Capital getCapital() {
return capital;
}
}

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/>
<bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
<constructor-arg index="0" type="java.lang.String" value="India" />
</bean>
<bean id="CaptialBean" class="org.arpit.javapostsforlearning.Capital">
<property name="capitalName" value="Delhi" />
</bean>
</beans>

Run it:

When you will run above application,you will get following as output.

Delhi is capital of India

@Autowired with Arugments:

By default,dependency is required in the case of @Autowired like @Required but you can turn off it by passing required=false to @Autowired as argument.

Country.java:

package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Autowired;
public class Country {

String countryName;
@Autowired(required=false)
Capital capital;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Capital getCapital() {
return capital;
}
}
Now it will run even if you don't provide capital bean in XML configuration.

Spring JSR 250 Annotations

Spring supports JSR 250 Annotations such as @PostConstruct, @PreDestroy and @Resource annotations.Lets  discuss each in brief.

@Resource:

Spring also supports injection using the JSR-250 @Resource annotation on fields or bean property setter methods. This is a common pattern found in Java EE 5 and Java 6 which Spring supports for Spring-managed objects as well.

@Resource takes name as attribute and by default Spring will interpret that value as the bean name to be injected. In other words, it follows by-name semantics.If you do not specify name attribute then it will interpret property name as bean name to be injected and then it will search in XML configuration file.

Example:

For configuring spring in your eclipse ide please refer hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Autowired;
public class Country {

String countryName;

@Resource(name="capitalA")
  Capital capital;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Capital getCapital() {
return capital;
}
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java

package org.arpit.javapostsforlearning;

public class Capital {

String capitalName;

public String getCapitalName() {
return capitalName;
}

public void setCapitalName(String capitalName) {
this.capitalName = capitalName;
}
}

3.QualifierAnnotationInSpringMain.java

This class contains main function.Create QualifierAnnotationInSpringMain.java under package org.arpit.javapostsforlearning.Copy following content into QualifierAnnotationInSpringMain.java

 package org.arpit.javapostsforlearning;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class QualifierAnnotationInSpringMain{

public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

Country countryObj = (Country) appContext.getBean("CountryBean");
String countryName=countryObj.getCountryName();
Capital capital=countryObj.getCapital();
String capitalName=capital.getCapitalName();
System.out.println(capitalName+" is capital of "+countryName);

}
}

4.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/>
<bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
<property name="countryName" value="India" />
</bean>
<bean id="capitalA" class="org.arpit.javapostsforlearning.Capital">
<property name="capitalNamehttp://www.blogger.com/blogger.g?blogID=1114068605611316469#editor/target=post;postID=2213204035101507334" value="Delhi" />
</bean>
<bean id="capitalB" class="org.arpit.javapostsforlearning.Capital">
<property name="capitalName" value="Mumbai" />
</bean>
</beans>

As you can note here we are having two beans of same type.In Country.java we have used @Resource(name-"capitalA") it means we want to autowire capital property of country with bean id="capitalA" in XML configuration file.

5.Run it:

When you will run above application,you will get following as output.

Delhi is capital of India

@PostContruct and @PreDestroy:

These annotations are alternative methods for defining initialization and destruction callback functions.
We have used all other method in Spring lifetime callbacks.

Example:

For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class Country {

String countryName ;

public String getCountryName() {
return countryName;
}


public void setCountryName(String countryName) {
this.countryName = countryName;
}

@PostConstruct
public void init()
{
System.out.println("In init block of country");
}

@PreDestroy
public void destroy()
{
System.out.println("In destroy block of country");
}
}

2.LifetimeCallbacksMain.java

This class contains main function.Create LifetimeCallbacksMain.java under package org.arpit.javapostsforlearning.Copy following content into LifetimeCallbacksMain.java
package org.arpit.javapostsforlearning;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class LifetimeCallbacksMain{

public static void main(String[] args) {

AbstractApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Country countryObj = (Country) appContext.getBean("country");
System.out.println("Country Name: "+countryObj.getCountryName());
appContext.registerShutdownHook();
}
}
Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.

3.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="country" class="org.arpit.javapostsforlearning.Country" init-method="init" destroy-method="destroy">
<property name="countryName" value="India"/>
</bean>

</beans>

4.Run it

When you will run above application,you will get following as output.


In init block of country
Country Name: India
In destroy block of country

@Qualifier Annotation in spring

you can have more than one bean of same type in your XML configuration but you want to autowire only one of them ,so @Qualifier removes confusion created by @Autowired by declaring exactly which bean is to autowired.

Example:

For configuring spring in your eclipse ide please refer hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Autowired;
public class Country {

String countryName;
@Autowired
@Qualifier("capitalA")
  Capital capital;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Capital getCapital() {
return capital;
}
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java

package org.arpit.javapostsforlearning;

public class Capital {

String capitalName;

public String getCapitalName() {
return capitalName;
}

public void setCapitalName(String capitalName) {
this.capitalName = capitalName;
}
}

3.QualifierAnnotationInSpringMain.java

This class contains main function.Create QualifierAnnotationInSpringMain.java under package org.arpit.javapostsforlearning.Copy following content into QualifierAnnotationInSpringMain.java

 package org.arpit.javapostsforlearning;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class QualifierAnnotationInSpringMain{

public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

Country countryObj = (Country) appContext.getBean("CountryBean");
String countryName=countryObj.getCountryName();
Capital capital=countryObj.getCapital();
String capitalName=capital.getCapitalName();
System.out.println(capitalName+" is capital of "+countryName);

}
}

4.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/>
<bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
<property name="countryName" value="India" />
</bean>
<bean id="capitalA" class="org.arpit.javapostsforlearning.Capital">
<property name="capitalName" value="Delhi" />
</bean>
<bean id="capitalB" class="org.arpit.javapostsforlearning.Capital">
<property name="capitalName" value="Mumbai" />
</bean>
</beans>

As you can note here we are having two beans of same type.In Country.java we have used @Qualifier("capitalA") it means we want to autowire capital property of country with bean id="capitalA" in XML configuration file.

5.Run it:

When you will run above application,you will get following as output.

Delhi is capital of India

@Required Annotation in spring

The @Required annotation applies to bean property setter methods, as in the following example:

package org.arpit.javapostsforlearning;

public class Country {

  Capital capital; 

  @Required
  public void setCapital(Capital capital) {
        this.capital = capital;
    }
}

This annotation simply indicates that the affected bean property must be populated at configuration time: either through an explicit property value in a bean definition or through autowiring. The container will throw an exception if the affected bean property has not been populated; this allows for eager and explicit failure, avoiding NullPointerExceptions or the like later on.

Suppose you have very large application and you get   NullPointerExceptions because required dependency has not been injected then it is very hard to find out what goes wrong.So this annotation helps us in debugging the code.

Example:

For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

package org.arpit.javapostsforlearning;
import org.springframework.beans.factory.annotation.Required;
public class Country {

    String countryName;
    Capital capital;
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public Capital getCapital() {
        return capital;
    }

  @Required
    public void setCapital(Capital capital) {
        this.capital = capital;
    }
}

2.Capital.java

This is also simple pojo class having one attribute called "capitalName".
Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java

package org.arpit.javapostsforlearning;

public class Capital {

    String capitalName;

    public String getCapitalName() {
        return capitalName;
    }

    public void setCapitalName(String capitalName) {
        this.capitalName = capitalName;
    }
}

3.RequiredAnnotationInSpringMain.java

This class contains main function.Create RequiredAnnotationInSpringMain.java under package org.arpit.javapostsforlearning.Copy following content into RequiredAnnotationInSpringMain.java

 package org.arpit.javapostsforlearning;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class RequiredAnnotationInSpringMain{

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");

        Country countryObj = (Country) appContext.getBean("CountryBean");
        String countryName=countryObj.getCountryName();
Capital capital=countryObj.getCapital();
        String capitalName=capital.getCapitalName();
        System.out.println(capitalName+" is capital of "+countryName);
      
    }
}

4.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/>
<bean id="CountryBean" class="org.arpit.javapostsforlearning.Country">
<property name="countryName" value="India" />
</bean>
<bean id="CaptialBean" class="org.arpit.javapostsforlearning.Capital">
<property name="capitalName" value="Delhi" />
</bean>
</beans>

Now you can note here that we have not injected capital property into country class but we have used it for getting capitalName in RequiredAnnotationInSpringMain class.

5.Run it:

When you will run above application,you will get following as output.

Sep 01, 2012 1:43:16 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@17a1767: startup date [Sat Sep 01 13:43:16 IST 2012]; root of context hierarchy
Sep 01, 2012 1:43:17 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [ApplicationContext.xml]
Sep 01, 2012 1:43:17 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@54446d: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,CountryBean,CaptialBean,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
Sep 01, 2012 1:43:17 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@54446d: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,CountryBean,CaptialBean,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CountryBean' defined in class path resource [ApplicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'capital' is required for bean 'CountryBean'
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at org.arpit.javapostsforlearning.SetterInjectionMain.main(SetterInjectionMain.java:11)
Caused by: org.springframework.beans.factory.BeanInitializationException: Property 'capital' is required for bean 'CountryBean'
    at org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.postProcessPropertyValues(RequiredAnnotationBeanPostProcessor.java:149)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    ... 11 more

When you run it,you will get exception complaining "Property 'capital' is required for bean 'CountryBean'"

Saturday, September 1, 2012

Annotation based Configuration in spring

This is 13 of 13 parts of tutorial series

Tutorial Content:



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.


Tuesday, August 21, 2012

Introduction to Spring Framework

Target Audience

This tutorial is designed for Java programmers who need to understand the Spring 3 framework and its application.

Prerequisites:

Before proceeding with this tutorial you should have a good understanding of the Java programming language.
This is 1 of 13 parts of tutorial series

Tutorial Content:


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

Introduction: 

Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development 

Features:

  • The basic concept of the Dependency Injection or Inversion of Control is that, programmer do not need to create the objects, instead just describe how it should be created. No need to directly connect your components and services together in program, instead just describe which services are needed by which components in a configuration file/xml file. The Spring IOC container is then responsible for binding it all up.
  • Spring contains and manages the life cycle and configuration of application objects.
  • Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.
  • Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.
  • The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS

 Architecture:

Spring is well-organized architecture consisting  of seven modules. Modules in the Spring framework are:
  1. Spring AOP:

    One of the key components of Spring is the AOP framework. AOP is used in Spring:
    • To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on Spring's transaction abstraction.
    • To allow users to implement custom aspects, complementing their use of OOP with AOP
  2. Spring ORM:

    The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.
      
  3. Spring Web:

    The Spring Web module is part of Spring?s web application development stack, which includes Spring MVC.
     
  4. Spring DAO:

    The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.
     
  5. Spring Context:

    This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.
      
  6. Spring Web MVC:

    This is the Module which provides the MVC implementations for the web applications.
      
  7. Spring Core:

    The Core package is the most import component of the Spring Framework.
    This component provides the Dependency Injection features. The BeanFactory  provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic.

Spring Framework Architecture

In next post,we will see dependency injection(ioc) in spring.