在 pom.xml 中指定默认参数并在命令行中覆盖它

Specifying a default argument in pom.xml and overriding it in the command line

我的主要 class 的唯一功能是从 xml 配置文件中读取,我目前在命令行中指定该文件。是否有可能在 pom.xml 中指定默认配置文件,因此如果程序是 运行 来自命令行而不传入参数,则读取该配置文件,但如果参数使用 -Dexec.args 传递默认值被覆盖?

先看看exec插件文档here

在您的 Maven 属性中指定您要查看的默认值 属性 my.custom.property

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>test.test</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.debug>true</maven.compiler.debug>
        <!-- frameworks -->

        <!-- properties -->
        <my.custom.property>MAVEN</my.custom.property>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.6.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>java</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <mainClass>test.Test</mainClass>
                    <arguments>
                        <argument>${my.custom.property}</argument>
                    </arguments>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

这里是javaclass

package test;

import java.util.stream.Stream;


public class Test {

    public static void main(String[] args) {
        Stream.of(args)
                .forEach(arg -> System.out.println("ARGUMENT " + arg));
    }
}

如果你执行 mvn compile exec:java 你应该会在某处看到输出 ARGUMENT MAVEN。如果您提供自己的论点,例如。 mvn compile exec:java -Dmy.custom.property=TEST 你应该在控制台的某处看到 ARGUMENT TEST。