java - pom 中的 Maven 配置文件

标签 java maven-2 pom.xml profiles

我正在尝试根据配置文件通过 maven 设置一些系统环境变量。 所以我的pom代码是

<profile>
    <id>dev</id>
    <activation>
           <property>
              <name>com.xxx.profile</name>
              <value>dev</value>
            </property>
    </activation>
    <properties>                
          <db-url>jdbc:postgresql://abc</db-url>                        
          <db-username>xxx</db-username>
          <db-pwd>yy</db-pwd>           
    </properties>           
  </profile>

所以当我构建项目时,我会 mvn clean install -Dcom.xxx.profile=dev

在代码中,我有

String urlDB = System.getProperty("db-url");
String username = System.getProperty("db-username");
String password = System.getProperty("db-pwd");

但是当我运行它时,所有这些变量都为空。

System.getProperty("com.xxx.profile") 确实给出了正确的答案......

想法?

最佳答案

Maven profiles documentaion指出激活部分包含触发配置文件的条件,例如对于您的情况,您需要系统属性“com.xxx.profile”具有值“dev”。基于此,您可以知道 System.getProperty("com.xxx.profile") 将返回正确的结果,因为该值已经存在于您的系统中(自配置文件触发后)。

进一步类似的问题Using the properties tag within maven profiles 。基本上,您定义的属性值将在过滤资源的过程中用于替换 ${propertiesKeys}。因此,通过使用属性您无需定义新的系统属性。 所需的 pom 设置(您要解析的 .properties 文件在哪里):

 <build>
     <resources>
         <resource>
              <directory>src/main/resources</directory>
              <filtering>true</filtering>
         </resource>
     </resources>  
 </build>

属性文件示例:

database.driverClassName=${database.driverClassName}
database.url=${database.url}

尽管这样您就不会读取系统属性,而是读取属性文件。

属性-maven-插件

properties-maven-plugin我想它正是你想要的。查看使用文档底部的“set-system-properties”。您将找到可与您的个人资料一起使用的代码。这是一个例子:

<project>
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0.0</version>
        <executions>
          <execution>
            <goals>
              <goal>set-system-properties</goal>
            </goals>
            <configuration>
              <properties>
                <property>
                  <name>db-url</name>
                  <value>${db-url}</value>
                </property>
              </properties>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

关于java - pom 中的 Maven 配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35947096/

相关文章:

java - Android MediaPlayer 可以播放压缩文件中的音频吗?

java - 如何在maven pom.xml中配置依赖项?

java - 在 Android 中将 Stream 转换为 String 时出现 OutOfMemoryError

maven-2 - Maven 中的版本传播

java - 如果没有任何变化,配置 Maven 不运行测试

java - 如何从依赖 war 中排除jar,仅用于在pom中运行测试

maven-2 - Maven 校验和 pom 设置?

java - Maven - 根据项目属性激活配置文件

java - 如何在 Selenium 中测试动态生成的元素

java - Android Eclipse 字符串 Txt + Edittext + 字符串 Txt = 崩溃