拥有一个Java Maven Web应用程序,其中包含以下配置文件中设置的硬编码属性:
的src /主/资源/ database.xml
<beans xmlns="http://www.springframework.org/schema/beans">
<bean id="aDatasource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
<property name="url"><value>jdbc:mysql://anIpAddress/mydatabase?zeroDateTimeBehavior=convertToNull</value></property>
<property name="username"><value>root</value></property>
<property name="password"><value>password</value></property>
</bean>
</beans>
的src /主/资源/ log4.j.properties
log4j.appender.RF.File=/opt/apache-tomcat-7.0.78/webapps/myapp/WEB-INF/classes/logs.log
在我运行maven clean install之前,我通过替换database.xml内部来不断编辑这些文件:
aniPAddress with localhost
root with my local database's root user
password with my local database's root password
在log4.properties中:
/opt/apache-tomcat-7.0.78/ with $CATALINA_HOME
问题(S):
e.g。
我应该在src / main / resources中创建一个包含以下属性的application.properties文件:
database.url = localhost
database.user = root
database.password =
tomcat.home = $CATALINA_HOME or /etc/tomcat7/
如何在database.xml和/或log4j.properties中显式设置这些?
e.g。
maven clean -install -p dev
maven clean -install -p prod
如何配置pom.xml文件以反映问题1中所需的行为?
答案 0 :(得分:3)
您可以使用资源过滤,请参阅https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html
鉴于以下pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>test</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<resources>
<resource>
<directory>${project.basedir}/src/main/filtered-resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<profiles>
<profile>
<id>dev</id>
<properties>
<jdbc.url>localhost</jdbc.url>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<jdbc.url>server.prod</jdbc.url>
</properties>
</profile>
</profiles>
</project>
文件src / main / filtered-resource / application.properties中的以下内容:
database.url = ${jdbc.url}
使用&#34; mvn -Pdev process-resource&#34;文件target / classes / application.properties将包含:
database.url = localhost
并使用&#34; mvn -Pprod process-resource&#34;:
database.url = server.prod
答案 1 :(得分:1)
找到关于如何在服务器启动时根据外部属性加载Spring数据源database.xml的第一个问题的答案:
就像将此条目放在database.xml文件中一样简单:
<bean id="propertyPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="true" />
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="location" value="file:/proplocation/database.properties"></property>
</bean>
没人知道Queston#2的答案?
有没有办法使用maven配置文件功能来切换配置属性?
e.g。
maven clean -install -p dev
maven clean -install -p prod