我有一个使用 Maven 构建的 Java EE 6 应用程序,在 NetBeans 7 中编写代码并部署在 GlassFish 3.1.2 上。当我接近完成时,我发现自己正在部署演示版本。
问题是我没有任何非常简单的方法来构建不同的环境,例如开发、QA、演示、产品等。对于某些东西,我一直在使用带有一堆返回的静态 getter 的 Java 类基于环境常量值的值。但这对我进行条件设置没有帮助
- javax.faces.PROJECT_STAGE (web.xml)
- 数据库凭证(glassfish-resources.xml)
- 邮件服务器(glassfish-resources.xml)
- JPA 日志记录级别 (persistence.xml)
可能还有一些我现在无法考虑的其他事情分散在 XML 文件中。
有没有办法定义这些配置文件的多个版本,并在构建时设置一个标志来选择环境,而在未指定环境时默认为 dev ?在这种情况下,有没有办法让 Maven 为我工作?
您可以使用maven http://maven.apache.org/为了实现这一点。特别是使用资源过滤 http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html.
首先,您可以定义配置文件列表:
<profiles>
<profile>
<id>dev</id>
<properties>
<env>development</env>
</properties>
<activation>
<activeByDefault>true</activeByDefault> <!-- use dev profile by default -->
</activation>
</profile>
<profile>
<id>prod</id>
<properties>
<env>production</env>
</properties>
</profile>
</profiles>
然后是你需要过滤的资源:
<build>
<outputDirectory>${basedir}/src/main/webapp/WEB-INF/classes</outputDirectory>
<filters>
<filter>src/main/filters/filter-${env}.properties</filter> <!-- ${env} default to "development" -->
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
然后基于配置文件的自定义属性src/main/filters
目录:
过滤器开发.properties
# profile for developer
db.driver=org.hsqldb.jdbcDriver
db.url=jdbc:hsqldb:mem:web
and
过滤器生产.properties
# profile for production
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/web?createDatabaseIfNotExist=true
要使用生产配置文件,您可以使用以下命令打包 warmvn clean package -Pprod
命令。
Here https://github.com/paukiatwee/webapp-bootstrap你可以在maven中看到使用profile的示例项目。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)