Spring Autowired

Spring Autowired annotation is configuration based which creates object of the bean.It can be implicitly registered by including the following below tag in an XML-based Spring configuration (notice the inclusion of the ‘context’ namespace):

<?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>

 

Note : only looks for annotations on beans in the same application context it is defined in. This means that, if you put in a WebApplicationContext for a DispatcherServlet, it only checks for @Autowired beans in your controllers, and not your services.

Let’s understand with simple example how we use it.

1. Create Address.java bean class as below:

package com.javahonk.di.bean;

public class Address {

    private String steetName;
    private String city;
    private String state;
    private String zip;

    public String getSteetName() {
        return steetName;
    }
    public void setSteetName(String steetName) {
        this.steetName = steetName;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public String getZip() {
        return zip;
    }
    public void setZip(String zip) {
        this.zip = zip;
    }

}

 

2. Create Person.java bean class and include Address class as properties with @Autowired annotation on it. Means spring will provide object of Address class at run-time and looks its properties in context file:

package com.javahonk.di.bean;

import org.springframework.beans.factory.annotation.Autowired;

public class Person {

    private String firstName;
    private String lastName;

    @Autowired
    private Address address;

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }

}

 

3. Now create context xml file and include beans of class Person and Address. Also include so that we can use annotation functionality.

<?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="person" class="com.javahonk.di.bean.Person">
	<property name="firstName" value="Mary"></property>
	<property name="lastName" value="Kay"></property>
</bean>

<bean id="address" class="com.javahonk.di.bean.Address">
	<property name="steetName" value="John st."></property>
	<property name="city" value="Edison"></property>
	<property name="state" value="NJ"></property>
	<property name="zip" value="10038"></property>
	<qualifier value="secondaryFoo"></qualifier>
</bean>

</beans>

 

4. Our all configuration realted to annotaion has done. Create main SpringAutowireAnnotation.java class to test it:

package com.javahonk;

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

import com.javahonk.di.bean.Person;

public class SpringAutowireAnnotation {

    public static void main(String[] args) throws Exception {

	ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
		"spring/springResourceContext.xml");
	applicationContext.getBean("person");
	Person person = applicationContext.getBean("person",
		Person.class);

	// We are getting person object using @Autowired functionality
	System.out.println("Steet: "
		+ person.getAddress().getSteetName() + " City: "
		+ person.getAddress().getCity() + " State: "
		+ person.getAddress().getState() + " Zip: "
		+ person.getAddress().getZip());

    }

}

 

As you see above we got applicationContext from xml file and get Person object using bean id person. As you remember we have added Address class properties in Person class which is using @Autowired annotation mean we can object of Address by using Person class object shown above test class.

Now main class as java application you will all properties value which has been set in xml file on console.

Spring Autowired

 

Below are summary of all @Autowired option which can be applied to bean:

1. @Autowired annotation may be applied to “traditional” setter methods:

package com.javahonk.di.bean;

import org.springframework.beans.factory.annotation.Autowired;

public class Mother {

    private Child child;

    @Autowired
    public void setChild(Child child) {
        this.child = child;
    }

}

 

2. The @Autowired annotation can also applied on constructors and fields:

package com.javahonk.di.bean;

import org.springframework.beans.factory.annotation.Autowired;

public class Mother {

    @Autowired
    private Child child;

    @Autowired
    public Mother(Child child) {
	this.child = child;
    }    

}

 

3. The annotation can also applied to methods with arbitrary names and/or multiple arguments:

package com.javahonk.di.bean;

import org.springframework.beans.factory.annotation.Autowired;

public class Mother {

    private Child child;

    @Autowired
    public void autoWiredTestApplied(Child child){
	this.child = child;
    }

}

 

4. It is also possible to provide all beans of a particular type from the ApplicationContext by adding the annotation to a field or method that expects an array of that type:

package com.javahonk.di.bean;

import org.springframework.beans.factory.annotation.Autowired;

public class Mother {

    @Autowired
    private Child[] child;   

}

 

5. It can be also use for typed collections:

package com.javahonk.di.bean;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

public class Mother {

    private Set<Child> childs;

    @Autowired
    public void setChilds(Set<Child> childs) {
        this.childs = childs;
    }

}

 

6. Even typed Maps may be autowired as long as the expected key type is String. The Map values will contain all beans of the expected type, and the keys will contain the corresponding bean names:

package com.javahonk.di.bean;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

public class Mother {

    private Map<String, Child> childMap;

    @Autowired
    public void setChildMap(Map<String, Child> childMap) {
	this.childMap = childMap;
    }

}

 

7. The autowiring will fail if no beans are available in context configuration file. The default behavior is to treat annotated methods, constructors, and fields as indicating required dependencies. This behavior can be changed as shown below.

package com.javahonk.di.bean;

import org.springframework.beans.factory.annotation.Autowired;

public class Mother {

    private Child child;

    @Autowired(required=false)
    public void setChild(Child child) {
	this.child = child;
    }

}

 

8. @Autowired may also be used for BeanFactory interface, the ApplicationContext interface, the ResourceLoader interface, the ApplicationEventPublisher interface and the MessageSource interface. These interfaces (and their extended interfaces such as ConfigurableApplicationContext or ResourcePatternResolver) will be automatically resolved, with no special setup necessary.

package com.javahonk.di.bean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

public class Mother {

    @Autowired
    private ApplicationContext context;

    public Mother() {

    }

    //...

}

 

That’s it for Spring Autowired

Spring Autowired   Download source code: Spring Autowired

Leave a Reply

Your email address will not be published. Required fields are marked *