正确地将 JDK 参数传递给 Maven pom 文件

Properly pass JDK argument into Maven pom file

因为我需要在 HTTP 请求中自定义主机 header,所以我需要使用以下参数启动我的 Spring 启动 Java 应用程序(自 JDK 12 起可用) :

java -jar -Djdk.httpclient.allowRestrictedHeaders=host application.jar

但是如何将它传递到 Maven pom.xml 文件中以便能够在由于缺少此标志而失败的测试中使用此参数?

我尝试通过以下方式使用 maven-compiler-plugin:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <compilerArgs>
            <arg>-Djdk.httpclient.allowRestrictedHeaders=host</arg>
        </compilerArgs>
    </configuration>
</plugin>

但是错了:

error: invalid flag: -Djdk.httpclient.allowRestrictedHeaders=host

以下示例也不起作用:

-jdk.httpclient.allowRestrictedHeaders=host

jdk.httpclient.allowRestrictedHeaders=host

所以我什至尝试了 spring-boot-maven-plugin

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <jvmArguments>-Djdk.httpclient.allowRestrictedHeaders=host</jvmArguments>
    </configuration>
</plugin>

但它也不起作用,因为在那种情况下,此标志将被忽略,并且当我 运行 mvn 测试时出现限制错误。当我 运行 java 使用此标志时,这不会发生。

您似乎配置了错误的插件。您说您需要 "be able to use this argument during tests",这意味着您应该配置 Maven Surefire Plugin

看看the example they have provided。也许你可以使用 systemProperties:

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M3</version>
        <configuration>
          <systemProperties>
            <property>
              <name>propertyName</name>
              <value>propertyValue</value>
            </property>
            [...]
          </systemProperties>
        </configuration>
      </plugin>

argLine方法:

<argLine>-Djava.endorsed.dirs=...</argLine>