带有依赖对象的构造函数注入

如果两个类之间存在HAS-A关系,我们首先创建依赖对象(被包含对象),然后将其作为主类构造函数的参数传递。在这里,我们的场景是Employee HAS-A Address。Address类的对象将被称为依赖对象。让我们首先看一下Address类:

Address.java

这个类包含三个属性,一个构造函数和一个toString()方法来返回这些对象的值。

package cn.javatiku;

public class Address {
    private String city;
    private String state;
    private String country;

    public Address(String city, String state, String country) {
        super();
        this.city = city;
        this.state = state;
        this.country = country;
    }

    public String toString() {
        return city + " " + state + " " + country;
    }
}

Employee.java

它包含三个属性:id,name和address(依赖对象),两个构造函数和一个show()方法来显示当前对象的记录,包括依赖对象。

package cn.javatiku;

public class Employee {
    private int id;
    private String name;
    private Address address; // Aggregation

    public Employee() {
        System.out.println("def cons");
    }

    public Employee(int id, String name, Address address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    void show() {
        System.out.println(id + " " + name);
        System.out.println(address.toString());
    }
}

applicationContext.xml

在这个XML文件中,我们为AddressEmployee类定义了bean。我们使用构造函数注入来将依赖的Address对象传递给Employee的构造函数。

<?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="a1" class="cn.javatiku.Address">
        <constructor-arg value="ghaziabad"></constructor-arg>
        <constructor-arg value="UP"></constructor-arg>
        <constructor-arg value="India"></constructor-arg>
    </bean>

    <bean id="e" class="com.javatpoint.Employee">
        <constructor-arg value="12" type="int"></constructor-arg>
        <constructor-arg value="Sonoo"></constructor-arg>
        <constructor-arg>
            <ref bean="a1"/>
        </constructor-arg>
    </bean>

</beans>

Test.java

在这个类中,我们创建了一个Spring BeanFactory,获取了ID为"e"的Employee bean,并调用了它的show()方法。

package cn.javatiku;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;

public class Test {
    public static void main(String[] args) {
          
        Resource r = new ClassPathResource("applicationContext.xml");
        BeanFactory factory = new XmlBeanFactory(r);
          
        Employee s = (Employee) factory.getBean("e");
        s.show();
          
    }
}

当你运行Test类时,它将创建一个ID为12,名为"Sonoo"的Employee对象,并且它关联的Address对象具有城市为"ghaziabad",州为"UP",国家为"India"的属性。然后,show()方法将打印这些信息。

标签: spring, Spring教程, Spring技术, Spring语言学习, Spring学习教程, Spring下载, Spring框架, Spring框架入门, Spring框架教程, Spring框架高级教程, Spring面试题, Spring笔试题, Spring编程思想