@Autowired Annotation in spring

Tutorial Content: Spring tutorial for beginners

    Introduction to spring framework Dependency injection(ioc) in spring Spring hello world example in eclipse Spring java based configuaration Dependency injection via setter method in spring Dependency injection via constructor in spring Spring Bean scopes with examples Initializing collections in spring Beans Autowiring in spring Inheritance in Spring Spring ApplicationContext Spring lifetime callbacks BeanPostProcessors in Spring Annotation based Configuration 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.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012