《Pro Spring》学习笔记之Bean的继承

来源:互联网 发布:战舰世界施佩伯爵数据 编辑:程序博客网 时间:2024/05/21 07:14

SimpleBean.java

 

package ch4_Extends;

public class SimpleBean {
  
private String name;
  
private String sex;
  
private String age;
public String getAge() {
    
return age;
}

public void setAge(String age) {
    
this.age = age;
}

public String getName() {
    
return name;
}

public void setName(String name) {
    
this.name = name;
}

public String getSex() {
    
return sex;
}

public void setSex(String sex) {
    
this.sex = sex;
}

}

 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"
    xsi:schemaLocation
="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="SimpleBean1" class="ch4_Extends.SimpleBean">
<property name="name">
    
<value>gaoxiang</value>
  
</property>
<property name="sex">
   
<value>male</value>
</property>
</bean>


<bean id="SimpleBean2"  class="ch4_Extends.SimpleBean" parent="SimpleBean1">
  
<property name="age">
    
<value>26</value>
  
</property>
</bean>
</beans>

 

测试代码:

 

package ch4_Extends;

import java.io.File;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;






public class TestSpring{
  
public static void main(String args[])  throws Exception{
      
//获取bean factory
      BeanFactory factory=(BeanFactory)getBeanFactory();  //使用子beanFactory
     
      
//bean1只有name和sex属性,而bean1继承bean1,不光有自己的age属性,同时继承了name和sex属性
      SimpleBean bean1=(SimpleBean)factory.getBean("SimpleBean1");
      System.out.println(bean1.getName()
+" "+bean1.getAge()+" "+bean1.getSex());
      SimpleBean bean2
=(SimpleBean)factory.getBean("SimpleBean2");
      System.out.println(bean2.getName()
+" "+bean2.getAge()+" "+bean2.getSex());
      
     
  }

  
public static BeanDefinitionRegistry getBeanFactory(){
      
//获取bean factory
      String realpath="";
   
         
//加载配置项
      realpath=System.getProperty("user.dir")+File.separator+"src"+File.separator+"ch4_Extends"+File.separator+"applicationContext.xml";
  
     
      XmlBeanFactory  factory
=new XmlBeanFactory(new FileSystemResource(realpath));
      
      
return factory;
  }

}

 

运行结果:

gaoxiang null male
gaoxiang 26 male

原创粉丝点击