Spring Beans AutoWiring

  • Facebook
  • Google
  • LinkedIn
  • Twitter

We provide bean configuration details in the spring configuration file and we specify the beans that will be injected in other beans using ref attribute. But spring also provides auto-wiring features where we can wire beans automatically with auto-wiring feature and no need to provide bean injection explicitly. Internally it uses setter or constructor injection.

Advantage of Autowiring

  • Using auto-wiring we need to write less code in the XML configuration file so we don`t need to write the code to inject the dependency explicitly.
  • Development will be fast.

Disadvantage of Autowiring

  • We cannot auto-wire primitives, Strings and Classes.
  • Explicit dependencies in property and constructor-arg settings always override the auto-wiring.
  • Auto-wiring is less exact than explicit wiring.

Here are the auto-wiring modes supported in spring bean.

Mode Description
no In this mode we must define bean references via <ref> element
byName Container checks the spring configuration file and looks for the bean having name or id attribute same as the property name. This mode is applied on Setter methods. If there is more than one bean of same class with different bean name in configuration file, the autowiring will take the matching bean name with class property name.
byType Autowiring performs based on the class type of property and allows a property to be autowired if there is exactly one bean of the property type in the container. This mode is applied on Setter methods and if there are multiple beans found with the same class type in beans configuration then a fatal exception is thrown. But if there is no bean of required class type in the container then no autowiring will performed and also no error is thrown.
constructor 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 "no" 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 String getName() {
		return name;
	}

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

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = 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 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" />
		<property name="address" ref="address" />
	</bean>
</beans>  

In above configuration file, we have created bean with name address of class Address which we need to do inject in Student bean. So no autowire means dependency injection will be achieved using ref attribute

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

For more details please see

Autowiring collaborators on http://docs.spring.io
      Advertisements