为dev/QA/prod配置Java EE 6

Dis*_*tum 3 java configuration maven properties-file java-ee-6

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

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

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

可能还有许多我现在都想不到的其他东西分散在XML文件中.

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

Pau*_*Wee 10

您可以使用maven来实现这一目标.特别是使用资源过滤.

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

  <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>
Run Code Online (Sandbox Code Playgroud)

然后,您需要过滤的资源:

  <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>
Run Code Online (Sandbox Code Playgroud)

然后根据src/main/filters目录中的配置文件自定义属性:

filter-development.properties

# profile for developer
db.driver=org.hsqldb.jdbcDriver
db.url=jdbc:hsqldb:mem:web
Run Code Online (Sandbox Code Playgroud)

filter-production.properties

# profile for production
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/web?createDatabaseIfNotExist=true
Run Code Online (Sandbox Code Playgroud)

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

在这里,您可以看到在maven中使用配置文件的示例项目.