Spring auto-wiring using @Autowired annotation

  • Facebook
  • Google
  • LinkedIn
  • Twitter

In earlier post we have seen spring auto-wiring through XML by using the autowire attribute in the bean configuration file. Now we are going to learn spring auto-wiring using @Autowired. We can use the @Autowired annotation on setter method, constructor, field and on an arbitrary method also.

Here are the @Autowired annotations examples.

@Autowired on Instance variable Example

We can use @Autowired annotation directly on properties so any number of fields can be auto-wired within a class.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>SpringExample</groupId>
	<artifactId>SpringExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.0.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.0.0.RELEASE</version>
		</dependency>
	</dependencies>

</project>

Address.java

package javatutsworld;

public class Address {
	private String city;
	private String state;

	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;
	}
}

Student.java

In this class we used @Autowired on the Address property so there is no Setter required for this property

package javatutsworld;

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

public class Student {
	private String name;
	@Autowired
	private Address addr;

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public Address getAddress() {
		return addr;
	}

}

spring-config.xml

Using @Autowired feature, we must include <context:annotation-config /> tag in our spring-config file.

<?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.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

	<context:annotation-config />
	
	<bean id="address" class="javatutsworld.Address">
		<property name="city" value="Saharanpur" />
		<property name="state" value="Uttar Pradesh" />
	</bean>

	<bean name="student" class="javatutsworld.Student">
		<property name="name" value="Deepak Kumar" />
	</bean>
</beans>  

MainApp.java

package javatutsworld;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javatutsworld.Student;
public class MainApp {
	public static void main(String[] args) {
		AbstractApplicationContext  context = new ClassPathXmlApplicationContext("spring-config.xml");
		Student student=(Student)context.getBean("student");
		System.out.println(student.getName());		
		System.out.println(student.getAddress().getCity());
		System.out.println(student.getAddress().getState());
        context.close();
    }
}

Output

Mar 12, 2017 12:11:25 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6576fe71: startup date [Sun Mar 12 12:11:25 EDT 2017]; root of context hierarchy
Mar 12, 2017 12:11:25 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
Mar 12, 2017 12:11:25 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@6576fe71: startup date [Sun Mar 12 12:11:25 EDT 2017]; root of context hierarchy
Deepak Kumar
Saharanpur
Uttar Pradesh

@Autowired on Setter Method Example

In this class we used @Autowired on the Setter method of this Address property

Student.java

package javatutsworld;

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

public class Student {
	private String name;
	private Address addr;

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	@Autowired
	public void setAddr(Address addr) {
		this.addr = addr;
	}

	public Address getAddr() {
		return addr;
	}

}

@Autowired on constructor Example

In this class we used @Autowired on the constructor of this class.

Student.java

package javatutsworld;

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

public class Student {
	private String name;
	private Address addr;

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	@Autowired
	public Student(Address addr) {
		this.addr = addr;
	}

	public Address getAddress() {
		return addr;
	}

}

Dependency Check: @Autowired will make dependency check to make sure proper auto-wiring on property. If spring not able to find matching bean for auto-wiring, then it throws an exception. If you don't dependency check, then use "required" attribute of @Autowired annotation, and set it false. Here is an example:

Student.java

package javatutsworld;

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

public class Student {
	private String name;
	private Address addr;

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	@Autowired(required=false)
	public Student(Address addr) {
		this.addr = addr;
	}

	public Address getAddress() {
		return addr;
	}

}

Spring @Qualifier annotation

@Qualifier is used to in spring. If a dependency class is configured for more than once in spring-config file then the IOC container will throw the Exception for bean ambiguity. So in this situation to resolve this type of problem we can use @Qualifier annotation with the @Autowired annotation.

spring-config.xml

In this config file we defined two beans address and address2 for the same class type.

<?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.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

	<context:annotation-config />
	
	<bean id="address" class="javatutsworld.Address">
		<property name="city" value="Saharanpur" />
		<property name="state" value="Uttar Pradesh" />
	</bean>
	<bean id="address2" class="javatutsworld.Address">
		<property name="city" value="Dehradun" />
		<property name="state" value="UA" />
	</bean>

	<bean name="student" class="javatutsworld.Student">
		<property name="name" value="Deepak Kumar" />
	</bean>
</beans>  

Student.java

In this class we use @Qualifier with @Autowired which tell the container for the required bean

package javatutsworld;

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

public class Student {
	private String name;
	@Autowired
	@Qualifier("address2")
	private Address addr;

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setAddress(Address addr){
		this.addr=addr;
	}
	public Address getAddress() {
		return addr;
	}

}

Output

Mar 21, 2017 4:50:37 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6576fe71: startup date [Tue Mar 21 04:50:37 EDT 2017]; root of context hierarchy
Mar 21, 2017 4:50:37 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
Deepak Kumar
Dehradun
UA

If we do not use @Qualifier("address2") with @Autowired then we will get below exception

Output

Mar 21, 2017 4:50:37 AM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@6576fe71: startup date [Tue Mar 21 04:50:37 EDT 2017]; root of context hierarchy



Mar 21, 2017 4:48:05 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6576fe71: startup date [Tue Mar 21 04:48:05 EDT 2017]; root of context hierarchy
Mar 21, 2017 4:48:05 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'student': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javatutsworld.Address javatutsworld.Student.addr; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javatutsworld.Address] is defined: expected single matching bean but found 2: address,address2
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
	at 

For more details please see Autowiring collaborators on http://docs.spring.io

      Advertisements