Spring4.0学习笔记005——Bean的配置三(基于XML文件)

Posted yfyzwr

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring4.0学习笔记005——Bean的配置三(基于XML文件)相关的知识,希望对你有一定的参考价值。

1. bean之间的关系

1-1. 继承

  • Spring 允许继承 bean 的配置,被继承的 bean 称为父 bean,继承这个父 Bean 的 Bean 称为子 Bean。

  • 子 Bean 从父 Bean 中继承配置, 包括父 Bean 的属性配置,同时子 Bean 也可以覆盖从父 Bean 继承过来的同名属性配置。

  • 父 Bean 可以作为配置模板,也可以作为 Bean 实例。 若只想把父 Bean 作为模板, 可以设置< bean >的abstract 属性为 true, 这样 Spring 将不会实例化这个 Bean。

  • 并不是< bean >元素里的所有属性都会被继承,比如: autowire, abstract 等。

  • 可以忽略父 Bean 的 class 属性, 让子 Bean 指定自己的类, 而共享相同的属性配置。但此时 父bean的abstract 属性必须设为 true。

下面同时示例来简单说明它的使用。

  1. 修改xml的配置。

    <bean id="Car" class="com.yfyzwr.spring.beans.Car">
        <property name="brand" value="baoma"></property>
        <property name="price" value="123"></property>
    </bean>
    
    <bean id="Car_son" parent="Car">
        <property name="price" value="1456"></property> 
        <!-- 继承Car的brand,但是price被自定义 -->
    </bean>
  2. 修改main方法的实现。

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
    Car car1 = (Car)context.getBean("Car_son");
    System.out.println(car1);
  3. 运行程序,查看结果。

    Car [brand=baoma, price=1456.0]

2. 使用其他的外部属性文件

在XML配置文件里配置 Bean 时, 有时需要在 Bean 的配置里混入系统部署的细节信息(如文件路径,数据源配置信息等), 而这些部署细节实际上需要和 Bean 配置相分离,保存在其他外部文件中。

Spring 提供一个PropertyPlaceholderConfigurer的BeanFactory后置处理器,这个处理器允许用户将Bean配置的部分内容移到“外部属性文件”中。可以在Bean配置文件里使用形式为$var的变量,PropertyPlaceholderConfigurer从外部属性文件里加载属性,并使用这些属性来替换变量。

Spring 2.0的用法如下所示。

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>environment.properties</value>
            <value>jdbc.properties</value>
        </list>
    </property>
</bean>


Spring 2.5之后,可通过< context:property-placeholder>元素简化。

  1. 在xml配置文件中添加context Schema定义(xml配置文件添加context命名空间)。

    xmlns:context="http://www.springframework.org/schema/context"
  2. 新建名为 car.properties 的外部属性文件,在其中写入某些属性。

    car.brand = BMW
    car.price = 123456

  3. 修改xml配置文件

    <!-- 导入外部属性文件 -->
    <context:property-placeholder location="car.properties"/>
    
    <!-- 导入外部属性文件,location属性后可接多个外部属性文件,以逗号隔开 -->
    <bean id="Car" class="com.yfyzwr.spring.beans.Car">
        <property name="brand" value="$car.brand"></property>
        <property name="price" value="$car.price"></property>
    </bean>
  4. 运行程序,查看运行 结果。

    Car [brand=BMW, price=123456.0]

以上是关于Spring4.0学习笔记005——Bean的配置三(基于XML文件)的主要内容,如果未能解决你的问题,请参考以下文章

Spring4.0学习笔记 —— 通过FactoryBean配置Bean

Spring4.0学习笔记003——Bean的配置一(基于XML文件)

Spring4.0学习笔记006——Bean的配置(基于注解)

Spring4.0学习笔记006——Bean的配置(基于注解)

Spring4.0学习笔记004——Bean的配置二(基于XML文件)

Spring4.0学习笔记 —— 自动装配