Spring Bean Autowiring byConstructor

The concept of Spring Autowiring by constructor is similar to spring autowiring byType but having a little bit difference, in byType we are using setter injection where as by Constructor, we are using constructor injection.

Let's see the same example for better clarity:

Required Files:

  • 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 = "constructor" >
    <
    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();
    }
}

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 | Data Science with Python Training | Projects

SILAN Technology, BBSR
Call to: 0674-2361252

Comment