(五)Spring 框架中Bean配置的继承

Spring支持bean配置继承。我们可以定义一个bean,然后进一步配置它来创建新的bean。

通过使用bean继承,我们可以共享公共值,属性或配置。

子bean继承其父bean配置,属性和属性。

此外,子bean可以覆盖继承的值。

Java Bean

package com.www.w3cschool.cnmon;
public class Customer {
    private int type;
    private String action;
    private String Country;
    public int getType() {
      return type;
    }
    public void setType(int type) {
      this.type = type;
    }
    public String getAction() {
      return action;
    }
    public void setAction(String action) {
      this.action = action;
    }
    public String getCountry() {
      return Country;
    }
    public void setCountry(String country) {
      Country = country;
    }
  @Override
  public String toString() {
    return "Customer [type=" + type + ", action=" + action + ", Country="
        + Country + "]";
  }
}

Bean配置文件

此外,子bean可以覆盖继承的值。...

<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-2.5.xsd">
  <bean id="generalCustomer" class="com.www.w3cschool.cnmon.Customer">
    <property name="country" value="USA" />
  </bean>
  <bean id="specialCustomer" parent="generalCustomer">
    <property name="action" value="backup" />
    <property name="type" value="1" />
  </bean>
</beans>

在上面“generalCustomer"bean的配置文件中包含国家财产的“美国"值。

在上面“generalCustomer"bean的配置文件中包含国家财产的“美国"值。...

这里是运行此应用程序的代码。

package com.www.w3cschool.cnmon;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App 
{
    public static void main( String[] args )
    {
      ApplicationContext context = 
      new ClassPathXmlApplicationContext("SpringBeans.xml");
      Customer cust = (Customer)context.getBean("specialCustomer");
      System.out.println(cust);
    }
}

上面的代码生成以下结果。

客户[type = 1,操作=备份,国家=美国]

转自:https://www.w3cschool.cn/wkspring/spring-bean-inheritance.html

猜你喜欢

转载自blog.csdn.net/jiangshangchunjiezi/article/details/88826173