Spring Autowiring byName

In this case, spring framework is trying to check the inner bean reference variable and inner bean id in configuration file is same or not. It should be same, that means if inner bean id found with id as property name then that class object will be injected into that property by calling setter injection. If no id is found then that property remains un-wired, but never throws any exception.

Let's see an example for better understanding.

Files required?

  • Address.java
  • Employee.java
  • spconfig.xml
  • Test.java

Address.java

package java8s;
public class Address {
private String city;
private String state;
public String getCity() {
return city;
}
public void setCity(String name) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state= state;
}
}

Employee.java

package java8s;
public class Employee {
private String name;
private Address ad;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAd() {
return ad;
}
public void setAd(Address ad) {
this.ad = ad;
}
public void show()
{
System.out.println("Employee Name :"+ name);
System.out.println("Employee Address :"+ ad.getCity()+" "+ ad.getState());
}
}

spconfig.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="id1" class="java8s.Employee" autowire="byName">
<property name="name" value="Trilochan Tarai" />
</bean>
<bean id="ad" class="java8s.Address">
<property name="city" value="Bhubaneswar" />
<property name="state" value="Odisha" />
</bean>
</beans>

Test.java

package java8s;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args)
{
Resource resource = new ClassPathResource("spconfig.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Object o = factory.getBean("id1");
Employee e = (Employee)o;
e.show();
}
}

Here We called id1 from Test.java, and in spconfig.xml we have written autowire=byName, so first it will checks for the class with id name ad and inserts ad class properties into that object and then injects value ?Employee Name? into name property of Employee class.

Output

Employee Name:Trilochan Tarai
Employee Address:Bhubaneswar Odisha

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment