Spring中配置属性的外在化

本文介绍如何在Spring框架中使用PropertyPlaceholderConfigurer进行属性的外置化配置,包括如何指定外部属性文件的位置,以及如何在Bean装配文件中使用占位符引用这些外部配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大多数情况下,我们可以在一个Bean装配文件里配置整个程序,但有的时候却需要把部分配置提取到单独的属性文件中,最常见的一种情形就是配置数据源。

 

在Spring里,如果使用ApplicationContext作为Spring容器(另一种是使用BeanFactory,ApplicationContext提供了更多的功能,所以大部分都是使用ApplicationContext作为Spring容器),属性的外在化就很容易,开发者可以使用Spring的PropertyPlaceholderConfigurer告诉Spring从外部属性文件加载特定的配置。为了启用这个特性,需要在Bean装配文件里配置如下的Bean:

  

 

 <bean id="propertyConfigurer"
           class="org.springframework.beans.factory.config. PropertyPlaceholderConfigurer">
    <property name="location" value="jdbc.properties"/><!-- value的按照具体情况取值-->
 </bean>

 loaction属性告诉Spring到哪里寻找属性文件。在本例中jdbc.properties文件中包含以下内容:

database.url=jdbc:hsqldb:Training
database.driver=org.hsqldb.jdbc.jdbcDriver
database.user=root
database.paseword=password

 

location属性可以处单个属性文件。如果需要把配置分散到多个属性文件中,应该使用PropertyPlaceholderConfigurer的locations(注意加了一个“s”)属性来设置属性文件的List。配置文件如下:

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

 

 

经过上述配置后,我们就可以在Bean装配文件里用占位变量代替硬编码的配置。从语法来说,占位变量的形式是${variable}。在使用占位变量之后,dataSource Bean的声明会是这样:

<bean id="datasource"
            class="org.springframework.jdbc.datasource.DriveManagerDataSource"><!--这种方式是基于JDBC驱动定义的数据源-->
     <property name="url" value="${database.url}"/>
     <property name="driverClassName"      
              value="${database.driver}"/>
     <property name="username" value="${database.user}"/>
     <property name="passeord" value="${database.passeord}"/>
</bean>

 当Spring创建dataSource Bean时,PropertyPlaceholderConfigurer会介入并用属性文件里的值替换占位变量。

 

     如附件中图所示 

 

 除了配置文件外,PropertyPlaceholderConfigurer还经常用于保存文本消息和实现国际化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值