大多数 SA 更愿意和更有信心处理 .properties 文件而不是 .xml。
Spring 提供PropertyPlaceholderConfigurer 让您将所有内容定义到一个或多个.properties 文件中,并替换applicationContext.xml 中的占位符。
在src/main/resources/文件夹下创建app.properties:
... ...
# Dadabase connection settings:
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://localhost:5432/app_db
jdbc.username=app_admin
jdbc.password=password
... ...
并像这样在applicationContext.xml 中使用 PropertyPlaceholderConfigurer:
... ...
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>app.properties</value>
</property>
</bean>
... ...
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
查看Spring PropertyPlaceholderConfigurer Example了解更多详情。
另外,从应用程序部署的角度来看,我们通常将应用程序打包成某种可执行格式,而.properties 文件通常打包在可执行的war 或ear 文件中。一个简单的解决方案是配置您的 PropertyPlaceholderConfigurer bean 以按照预定义的顺序从多个位置解析属性,因此在部署环境中,您可以使用固定位置或环境变量来指定属性文件,同时注意为了简化SA 的部署/配置任务,我们通常使用单个外部 .properties 文件定义所有运行时配置,如下所示:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<!-- Default location inside war file -->
<value>classpath:app.properties</value>
<!-- Environment specific location, a fixed path on server -->
<value>file:///opt/my-app/conf/app.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="true"/>
</bean>
希望这会有所帮助。