Spring Beans AutoWiring constructor Example

  • Facebook
  • Google
  • LinkedIn
  • Twitter

Constructor autowiring mode is similar to byType but only difference is that this mode is applied on constructor arguments and if there are multiple beans found with the same class type in beans configuration then a fatal exception is thrown if default constructor is not defined. But if there is no bean of required class type in the container then no autowiring will performed and exception will be thrown.

Spring Bean Autowire "constructor" Example

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

package javatutsworld;

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

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

	public Student(Address address) {
		this.address = address;
	}

	public String getName() {
		return name;
	}

	public Address getAddress() {
		return address;
	}

}

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

	<bean class="javatutsworld.Address">
		<property name="city" value="Saharanpur" />
		<property name="state" value="Uttar Pradesh" />
	</bean>
	<bean name="student" class="javatutsworld.Student" autowire="constructor">
		<property name="name" value="Deepak Kumar" />
	</bean>
</beans>  

In above configuration file, we have created one bean for Address class. So using attribute autowire="constructor". Autowiring will be performed without issue.

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

But if there is more than one bean of same class type in the configuration file and using autowire="constructor" then error is thrown and autowiring will not be performed like below.

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

	<bean class="javatutsworld.Address">
		<property name="city" value="Saharanpur" />
		<property name="state" value="Uttar Pradesh" />
	</bean>
	<bean class="javatutsworld.Address">
		<property name="city" value="Meerut" />
		<property name="state" value="Uttar Pradesh" />
	</bean>
	
	<bean name="student" class="javatutsworld.Student" autowire="constructor">
		<property name="name" value="Deepak Kumar" />
	</bean>
</beans>  

Output

Mar 12, 2017 2:17:02 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6576fe71: startup date [Sun Mar 12 14:17:02 EDT 2017]; root of context hierarchy
Mar 12, 2017 2:17:02 PM 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.UnsatisfiedDependencyException: Error creating bean with name 'student' defined in class path resource [spring-config.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [javatutsworld.Address]: : No qualifying bean of type [javatutsworld.Address] is defined: expected single matching bean but found 2: javatutsworld.Address#0,javatutsworld.Address#1; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javatutsworld.Address] is defined: expected single matching bean but found 2: javatutsworld.Address#0,javatutsworld.Address#1
	at 

But if add default constructor in Student.java then this exception will not come

public Student() {
 System.out.println("default constructor");
}

Output

Mar 12, 2017 2:59:44 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-config.xml]
default constructor
Exception in thread "main" Deepak Kumar

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

      Advertisements