spring引入外部属性文件

有时候我们并不想把所有的配置信息都放到spring的配置文件中,这样的话也不太好维护,比如说数据库的信息

<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
    <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8"/>
    <property name="username" value="root"/>
    <property name="password" value="123456"/>
</bean>

这样配置当然也可以,只是要去修改spring配置文件的时候由于spring的配置文件内容太多,不太方便,所以有时候会引入外部的属性文件

可以使用<context:property-placeholder>标签来进行引入

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   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-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 引入外部配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
  <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
    <property name="url" value="${url}"/>
    <property name="username" value="${username}"/>
    <property name="password" value="${password}"/>
  </bean>

db.properties属性文件

url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
username=root
password=123456

<context:property-placeholder>会生成一个PropertySourcesPlaceholderConfigurer类来解析占位符


爱逃课的篮球
7 声望1 粉丝