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>