1、用PropertyPlaceholderConfigurer,所包内的文件引用映射到包外文件
简化写法:
<context:property-placeholder location="classpath:/jdbc.propertes,file:/etc/myapp/jdbc.properties" igonre-resource-not-found="true" />
详细写法:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
<property name="location" value="file:${APP_HOME}/conf/mypage.properties"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
参考链接:http://outofmemory.cn/code-snippet/3708/spring-properties-file-location
2、把配置项设为maven参数,方便打包时可配置
src/main/resources/jdbc.properties:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=${jdbc.databaseurl}
jdbc.username=${jdbc.username}
jdbc.password=${jdbc.password}
pom.xml:
<project ...>
...
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
...
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<jdbc.databaseurl>jdbc:mysql://127.0.0.1/mydb</jdbc.databaseurl>
<jdbc.username>username</jdbc.username>
<jdbc.password>password</jdbc.password>
</properties>
...
</profile>
<profile>
<id>prod</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<jdbc.databaseurl>jdbc:mysql://212.123.45.6/mydb</jdbc.databaseurl>
<jdbc.username>username</jdbc.username>
<jdbc.password>secret-password</jdbc.password>
</properties>
...
</profile>
</profiles>
...
</project>