1.Spring使用properties资源文件作为配置源,配置取classPath下面的.
工程中难免出现一些需要每次部署都需要配置的参数,如数据库连接参数等,测试环境跟实际运行环境是不一样的。
将这些参数独立到一个配置文件并可以让spring方便加载注入。使用java的properties资源文件,将所有的配置参数都写到properties文件里面,使用${key}来在spring配置文件里面得到这个参数。
例:
1.1.property文件db-config.properties:
jdbc.url=jdbc:postgresql://127.0.0.1:3306/DB_name
jdbc.username=test
jdbc.password=test
1.2.在springContext的配置文件中配置:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="location" value="classpath:db-config.properties"/>
</bean>
1.3.数据源配置:
<bean id="DataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="org.postgresql.Driver"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
2.Spring使用properties资源文件作为配置源,配置文件与工程分离(与war包分离,可存于服务器中).
好处:.测试环境跟实际运行环境是不一样,避免生产环境上面每次部署修改配置信息。
配置分离提高系统安全性
2 .1.property文件db-config.properties:
jdbc.url=jdbc:postgresql://127.0.0.1:3306/DB_name
jdbc.username=test
jdbc.password=test
2.2.在springContext的配置文件中配置:
JBOSS下面可以在 exportCONF_PATH=/app/appconf/$JBOSS_CONF -------$JBOSS_CONF为实例名称
- -环境相关的配置文件路径 /app/appconf/<实例名>
<pre class="java" name="code"><bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="location" value="file:D:/dbconfig/db-config.properties"/>
<!--路径配置在startJBOSS.sh里面 <property name="location" value="file:${CONF_PATH}/db-config.properties"/>-->
</bean>
JAVA代码获取
String confPath = System.getenv().get("CONF_PATH");
InputStream in = new FileInputStream(new File(confPath + "/sysconfig.properties"));
Properties properties = new Properties();
properties.load(in);
2.3.数据源配置:
<bean id="DataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="org.postgresql.Driver"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>