为dev / QA / prod配置Java EE 6

时间:2012-05-27 07:08:38

标签: java maven configuration java-ee-6 properties-file

我有一个Java EE 6应用程序,我使用Maven构建,代码在NetBeans 7中并在GlassFish 3.1.2上部署。当我接近完成时,我发现自己正在部署演示版本。

问题是我没有任何简单的方法来构建不同的环境,例如dev,QA,demo,prod等。对于某些东西,我一直在使用Java类一堆静态getter,它们根据环境常量的值返回值。但这并没有帮助我有条件地设置

  • javax.faces.PROJECT_STAGE(web.xml)
  • 数据库凭据(glassfish-resources.xml)
  • 邮件服务器(glassfish-resources.xml)
  • JPA日志记录级别(persistence.xml)

现在我可以考虑的其他一些分散在XML文件中的东西。

有没有办法定义这些配置文件的多个版本,只是在构建时设置一个标志来选择环境,而在没有指定环境时默认为dev?在这种情况下,有没有办法让Maven为我工作?

3 个答案:

答案 0 :(得分:8)

您可以使用maven来实现这一目标。特别是使用resource filtering

首先,您可以定义配置文件列表:

  <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目录中的配置文件自定义属性:

<强> filter-development.properties

# profile for developer
db.driver=org.hsqldb.jdbcDriver
db.url=jdbc:hsqldb:mem:web

<强> filter-production.properties

# profile for production
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/web?createDatabaseIfNotExist=true

要使用生产配置文件,您可以使用mvn clean package -Pprod命令打包战争。

Here您可以在maven中看到使用配置文件的示例项目。

答案 1 :(得分:0)

这不是对问题的直接回应。这解释了管理env属性的差异策略 另一种管理diff env属性的方法是使用数据库来存储属性。这样您只需要管理数据库的配置。根据您指向的DB,您可以从该DB加载属性。如果使用spring而不是spring,则可以使用PropertyPlaceholderConfigurer来初始化DB中的属性。此方法允许您在不进行构建的情况下更改属性值。

如果您想要推广QA \ Testing团队测试的工件,这种方法很有用。在这种情况下,DB配置将不是构建过程生成的工件的一部分。

答案 2 :(得分:0)

如果需要配置web.xml,请检查以下方法: https://community.jboss.org/docs/DOC-19076

它使用与另一个答案中描述的相同的方法(资源过滤)。