gpt4 book ai didi

java - pom 中的 Maven 配置文件

转载 作者:行者123 更新时间:2023-12-02 03:50:11 25 4
gpt4 key购买 nike

我正在尝试根据配置文件通过 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com