首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

流入和BeanFactory嵌套

2012-08-27 
注入和BeanFactory嵌套首先是子BeanFactory:?xml version1.0 encodingUTF-8?beans xmlnshttp:/

注入和BeanFactory嵌套
首先是子BeanFactory:

<?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.xsd">    <bean id="name" ref="name"/>        <property name="age" value="2"/>        <property name="height" value="0.8"/>        <property name="isProgrammer" value="false"/>        <property name="ageInSeconds" value="63072000"/>    </bean>    <bean id="injectSimpleChild2" value="2"/>        <property name="height" value="0.8"/>        <property name="isProgrammer" value="false"/>        <property name="ageInSeconds" value="63072000"/>    </bean></beans>

然后是父BeanFactory:
<?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.xsd">    <bean id="name" ref="name"/>        <property name="age" value="2"/>        <property name="height" value="0.8"/>        <property name="isProgrammer" value="false"/>        <property name="ageInSeconds" value="63072000"/>    </bean></beans>

运行程序如下:
package com.apress.prospring2.ch03.beanfactory;import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.core.io.ClassPathResource;/** * @author janm */public class HierarchicalBeanFactoryDemo {    public static void main(String[] args) {        XmlBeanFactory parent = new XmlBeanFactory(new ClassPathResource("/META-INF/spring/injectdemo2-context.xml"));        XmlBeanFactory child = new XmlBeanFactory(new ClassPathResource("/META-INF/spring/injectdemo3-context.xml"), parent);        System.out.println(parent.getBean("injectSimpleParent"));        System.out.println(child.getBean("injectSimpleChild"));        System.out.println(child.getBean("injectSimpleChild2"));    }}

结果如下:
Name: John SmithAge: 2Age in Seconds: 63072000Height: 0.800000Is Programmer?: falseName: Johnny SmithAge: 2Age in Seconds: 63072000Height: 0.800000Is Programmer?: falseName: John SmithAge: 2Age in Seconds: 63072000Height: 0.800000Is Programmer?: false

第一个子xml引的是自己BeanFactory的name,第二个是引的父类的Name,所以在创建Factory的时候必须指明是引的哪个父BeanFactory。

热点排行