【发布时间】:2011-10-31 01:38:43
【问题描述】:
我有一个简单的 spring mvc 应用,使用 maven 和 intellij。
您如何为生产和开发创建单独的文件?
例如说我要为nhibernate设置一个生产开发mysql连接字符串?
我怎样才能让它在我构建时使用正确的文件来获取配置信息? (以及关于文件命名约定的任何建议?)
【问题讨论】:
标签: java spring spring-mvc intellij-idea
我有一个简单的 spring mvc 应用,使用 maven 和 intellij。
您如何为生产和开发创建单独的文件?
例如说我要为nhibernate设置一个生产开发mysql连接字符串?
我怎样才能让它在我构建时使用正确的文件来获取配置信息? (以及关于文件命名约定的任何建议?)
【问题讨论】:
标签: java spring spring-mvc intellij-idea
使用 ant 任务非常简单。
首先,在您的pom 中的<project> 下创建一对个人资料:
<profiles>
<profile>
<id>build-dev</id>
<activation>
<!-- <activeByDefault>true</activeByDefault> -->
<property>
<name>env</name>
<value>dev</value>
</property>
</activation>
<properties>
<config.name>config.dev.properties</config.name>
</properties>
</profile>
<profile>
<id>build-prod</id>
<activation>
<property>
<name>env</name>
<value>prod</value>
</property>
</activation>
<properties>
<config.name>config.prod.properties</config.name>
</properties>
</profile>
</profiles>
然后使用maven-antrun-plugin
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>prepare-package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<delete file="${project.build.outputDirectory}/config.properties"/>
<copy file="src/main/resources/${config.name}" tofile="${project.build.outputDirectory}/config.properties"/>
<delete file="${project.build.outputDirectory}/config.dev.properties"/>
<delete file="${project.build.outputDirectory}/config.prod.properties"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
现在您只需在运行mvn 时指定所需的配置文件。如果您想要默认值,请取消注释并放置:
<!-- <activeByDefault>true</activeByDefault> -->
默认情况下您想要的配置文件中的部分。实际上,如果两者都未指定,则构建将在 ant 任务上失败。
【讨论】:
有很多方法可以解决这个问题。
一般来说,数据库连接字符串之类的内容可以进入属性文件,并在 Spring XML 配置文件中使用PropertyPlaceholderConfigurer 替换。一个常见的技巧是创建一个自定义实现,查找-D 启动参数、用户名、机器名等,这些可以用来决定实际使用哪个属性文件。
同样的技巧也可以用于 Spring 配置文件,方法是创建一个 XmlWebApplicationContext 的实现(?我永远不记得要子类化什么),它添加/修改默认 getConfigLocations 以添加,比如说,以文件开头的文件用户名或机器名、-D 启动参数值等。
顺便说一句,如果您使用的是 Java,那么您不是在使用 NHibernate,而是在使用 Hibernate。
编辑 Brian 的方法是“多种方式”中的一种,我只是想在不构建的情况下保持它的可配置性,即基于任意“本地”条件等动态,所以我可以交换事情真的很容易解决。
【讨论】: