在Spring,Maven和Eclipses中处理XML文件中的属性值的最佳方法

tec*_*012 18 eclipse svn spring spring-mvc maven

我正在开发一个Spring WebFlow项目,它在XML文件中有很多属性值,正如Spring程序员所知道的那样.我有数据库用户名,密码,URL等.

我们正在使用Eclipse与Spring WebFlow和Maven.我们正在尝试让SA执行构建,但SA不想进入XML文件来更改值,但另一方面,我们不知道生产值.我们如何使用它?

yor*_*rkw 40

大多数SA更愿意和自信地处理.properties文件而不是.xml.

Spring提供PropertyPlaceholderConfigurer,允许您将所有内容定义到一个或多个.properties文件中,并替换占位符applicationContext.xml.

创建一个app.properties下层src/main/resources/文件夹:

... ...

# Dadabase connection settings:
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://localhost:5432/app_db
jdbc.username=app_admin
jdbc.password=password

... ...
Run Code Online (Sandbox Code Playgroud)

并使用PropertyPlaceholderConfigurer applicationContext.xml:

... ...

<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>
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请查看Spring PropertyPlaceholderConfigurer示例.

此外,从应用程序部署的角度来看,我们通常以某种可执行格式打包应用程序,而.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>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.