Spring配置分离、配置文件与项目分离

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>
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值