在Spring中使用继承的Bean

通过使用bean的parent属性,我们可以指定bean之间的继承关系。在这种情况下,父bean的值将被继承到当前bean。

让我们看一个简单的继承Bean的例子。

Employee.java

这个类包含三个属性,三个构造函数和show()方法来显示值。

package cn.javatiku;

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

    public Employee() {}

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

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

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

Address.java

package cn.javatiku;

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

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

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

applicationContext.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="e1" class="cn.javatiku.Employee">
        <constructor-arg value="101" />
        <constructor-arg value="Sachin" />
    </bean>

    <bean id="address1" class="cn.javatiku.Address">
        <constructor-arg value="21,Lohianagar" />
        <constructor-arg value="Ghaziabad" />
        <constructor-arg value="UP" />
        <constructor-arg value="USA" />
    </bean>

    <bean id="e2" class="cn.javatiku.Employee" parent="e1">
        <constructor-arg ref="address1" />
    </bean>

</beans>

Test.java

package cn.javatiku;

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 r = new ClassPathResource("applicationContext.xml");
        BeanFactory factory = new XmlBeanFactory(r);

        Employee e1 = (Employee) factory.getBean("e2");
        e1.show();
    }
}

在这个例子中,我们定义了两个Employee对象,其中一个是e1,另一个是e2,e2继承了e1的属性。e1中的id和name属性在e2中也被继承了。我们在applicationContext.xml中使用parent属性来定义e2继承e1。

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