【问题标题】:System property is always null in maven projectMaven项目中的系统属性始终为空
【发布时间】:2018-11-24 10:42:10
【问题描述】:

我的实用类

Properties prop = new Properties();
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        String profile = System.getProperty("env");
        //InputStream in = loader.getResourceAsStream(fileName + ".properties");
        InputStream in = loader.getResourceAsStream(fileName + "_" + profile + ".properties");

总是返回 null。

我确实在 pom 中添加了 properties-maven-plugin

<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>env</name>
                                <value>prod</value>
                            </property>
                        </properties>
                    </configuration>
                </execution>
            </executions>
        </plugin>

但在 util 类中获取属性值仍然没有运气。

【问题讨论】:

  • String env = System.getProperty("env");: 这段代码在哪里,什么时候运行?
  • 你运行哪个 Maven 目标?
  • @MoritzPetersen 是的。没有运气

标签: java maven maven-3 maven-plugin


【解决方案1】:

作为旁注 - 如果您在看到错误时使用 surefire 运行它,您可能应该使用其内置的系统属性功能:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <systemPropertyVariables>
            <env>prod</env>
        </systemPropertyVariables>
    </configuration>
</plugin>

【讨论】:

    【解决方案2】:

    你试过了吗?

    <systemProperties>
        <systemProperty>
            <name>env</name>
            <value>prod</value>
        </systemProperty>
    </systemProperties>
    

    【讨论】:

      【解决方案3】:

      据我了解set-system-properties 目标的文档,它在当前机器上设置环境变量。根据它的做法,这些环境变量可以仅在构建期间定义,也可以仅在当前用户中定义,或者,如果您还拥有当前机器的管理员权限。

      无论如何,它只会在构建项目的机器上设置变量。

      如果我正确理解您的问题,您想存储构建是 release(生产)还是 debug 构建?

      在这种情况下,您可以使用maven-assembly-plugin 并定义一个清单值。此清单值将写入 jar 的清单,您可以在运行时读取它,例如。 G。使用 JCabi Manifest 库。

      【讨论】:

        猜你喜欢
        • 2011-03-14
        • 1970-01-01
        • 2014-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        相关资源
        最近更新 更多