spring的配置文件中引入其他配置

1.引入

       我们在做项目的时候会遇到这种情况

       1)有些参数在某些阶段中是常量

             比如在开发阶段连接数据库时的连接driverClass,url,username,password等;配置文件的位置

       2)而这些参数在不同阶段之间又往往需要改变

             比如在生产环境和开发环境连接的数据库往往是不同的


       那么我们就希望有一种解决方案,可以方便我们在一个阶段内不需要频繁书写一个参数的值,而在不同阶段又可以方便的切换参数配置信息


2.使用placeHoder

        只需要在spring的配置文件中添加

<context:property-placeholder location="classpath:jdbc.properties"/>
        这里的location为参数配置文件的位置,参数配置文件通常放置在src目录下,而参数配置文件可以直接写成properties文件即可,例如

        或者直接定义不用注解:

     <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>      
                <value>classpath:/jdbc.properties</value>
            </list>      
        </property>      
    </bean> 
       效果是一样的

#jdbc配置

test.jdbc.driverClassName=com.mysql.jdbc.Driver
test.jdbc.url=jdbc:mysql://localhost:3306/test
test.jdbc.username=root
test.jdbc.password=root

        这样一来,就可以在spring配置的bean的属性设置值了,比如spring有一个jdbc数据源的类DriverManagerDataSource

        这配置文件中如下定义bean

<bean id="testDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
     <property name="driverClassName" value="${test.jdbc.driverClassName}"/>
     <property name="url" value="${test.jdbc.url}"/>
     <property name="username" value="${test.jdbc.username}"/>
     <property name="password" value="${test.jdbc.password}"/>
</bean>

3.使用import resource

        实际上就是将spring配置按模块拆分,然后再引入进来即可

        模块spring配置文件:

<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="office" class="com.mycompany.app.Office">
        <property name="officeNo" value="002"/>
    </bean>
    <bean id="car" class="com.mycompany.app.Car">
        <property name="brand" value=" 红旗 CA72"/>
        <property name="price" value="7788"/>
    </bean>
</beans>
      总的配置文件:

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-2.5.xsd
">
    <import resource="classpath:newBean.xml"/>

    <context:annotation-config/> 
    <bean id="boss" class="com.mycompany.app.Boss"/>
</beans>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值