Advertisement



< Prev
Next >



Autowiring with byName



In our last tutorial, we understood how to perform Dependency Injection using Annotation, in this tutorial we are going to understand about how to perform Dependency Injection using the Autowiring feature of Spring Framework.

Autowiring is a feature provided by Spring Framework which automate the process of wiring the beans in a Spring Project. To perform autowiring of beans, Spring provides us an attribute -autowire.


Attribute autowire may have any of the three values -


What does autowire="byName" do?


When a class A contains a property/reference of class B and the autowire attribute is set with the byName value on class A bean(configured in xml file), the Spring container looks for the other bean(in xml) of type class B with the same property name and inject it into the class A bean.

In the upcoming section, we are going to create a few loosely coupled Java classes also known as beans, configure these beans in a configuration xml file, load and instantiate the beans and perform dependency injection using the autowire attribute value - byName.



Creating the Java class - Company


We are going to create a java class named Company within the decodejava package and this class contains a message info().

package decodejava;

public class Company
{
	
	public void info() 
	{
		System.out.println("Company A");	
	}

}





Dependent Class containing a Company object - Employee


Next, we are going to create another Java class named Employee and it is going to contain a String object, a primitive int and an Company reference, hence Employee class is dependent on Company class as it contains its reference.

The objects of String class and Company class and primitive int value will be injected into a Employee instance/bean by an automatic call to the setter methods(must have when using autowire="byType") in the Employee class by the Spring Container, when the Employee bean is created by it using the configuration xml file(to be created in the upcoming section).


package decodejava;

public class Employee
{
	Company company;
	String name;
	int yearsOfExp;
	
	
	//Setter method is a must when using autowire="byName"
	public void setName(String name) 
	{
		this.name = name;
	}
	public String getName()
	{
		return name;
	}
	
	
	
	
	//Setter method is a must when using autowire="byName"
	public void setCompany(Company company) 
	{
		this.company = company;
	}
	
	public Company getCompany()
	{
		return company;
	}


	
	
	//Setter method is a must when using autowire="byName"
	public void setYearsOfExp(int yearsOfExp) 
	{
		this.yearsOfExp = yearsOfExp;
	}
	
	public int getYearsOfExp()
	{
		return yearsOfExp;
	}
}



Advertisement




Adding the Utility class that calls the Spring API


Next, we are going to create another class named - Utility, which is a simple java class. The Utility class uses the ApplicationContext container(an interface) of Spring Framework by creating its instance using its implemented class FileSystemXmlApplicationContext, which -

Eventually this class calls the method of Employee class - getName() and getYearsOfExp.

Utility.java
package decodejava;

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

public class Utility 
{
	public static void main(String[] args) 
	{
		ApplicationContext context = new FileSystemXmlApplicationContext("classpath:config.beans.xml");
		Employee employeeBean = context.getBean("EmployeeBean", Employee.class);
		System.out.println("Employee Name : " + employeeBean.getName());
		System.out.println("Years of experience : " + employeeBean.getYearsOfExp());
		employeeBean.getCompany().info();
	}
}





Adding a configuration file


Next, we are going to add a configuration file to our project. This configuration document is an Extensible Markup Language(XML) file, ending with .xml extension and we are going to name file as config.beans.xml.

In this file, we have configured an Employee bean with a unique id, a String object, a primitive int value and a Company bean is injected into the Employee bean with the same property name as present in the Employee class, using the autowire byName attribute..


config.beans.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 ="EmployeeBean" class="decodejava.Employee" autowire = "byName">
	<property name="name" value="Employee1"/>
	<property name="yearsOfExp" value="7"/>
</bean>


<bean id ="company" class="decodejava.Company">
</bean>

</beans>
 



This mapping document has a parent <beans> tag as the root element and its individual child elements, each with a <bean> tag, containing all the attributes such as -


Adding JARs


  • We are going to add some JARs files to our Java project. These JARs are required in order to successfully execute a Spring project.

    All these JARs are included in the folder named libs(within our Spring installation folder). So, we need to add all the JARs in the libs folder to our build path of our Java project.

    Note : Those who don't know how to add JARs to the build path of your Java project in Eclipse IDE, please refer to our section Adding JARs to your Spring project in Eclipse.






Directory Structure of Project




The picture above depicts how and where to arrange classes and interfaces comprising this Spring Project, in a specific directory structure.

Project Folder - SpringDependencyInjectionAutowireByName is the name of our Project and it is a top-level directory.






Execution


Finally, after executing Utility class, you will get the following output within the Console window. This output shown below, shows how the Utility class has used the ApplicationContext container of Spring Framework to load the configuration xml file - config.beans.xml, access the beans specified in it, instantiate the Company class and Employee class.

It also injects a String object, a primitive int value and a Company bean into Employee bean and calls the methods of the respective classes.

Jul 17, 2018 11:21:23 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@1ee0005: startup date [Tue Jul 17 11:21:23 IST 2018]; root of context hierarchy
Jul 17, 2018 11:21:23 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [config.beans.xml]
Employee Name : Employee1
Years of experience : 7
Company A


This concludes performing the dependency injection by injecting a bean into another bean using the autowire attribute value - byName. In the next article, we are going to show you how to perform the dependency injection using the autowire attribute value - byType.




Please share this article -




< Prev
Next >
< Autowiring with byName
Autowiring with byType



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement