知識庫 / Spring / Spring Boot RSS 訂閱

Spring Boot命令行參數

Spring Boot
HongKong
6
02:05 PM · Dec 06 ,2025

1. 概述

在本快速教程中,我們將學習如何將命令行參數傳遞到 Spring Boot 應用程序。

我們可以使用命令行參數來配置我們的應用程序、覆蓋應用程序屬性以及傳遞自定義參數。

2. Maven命令行參數

首先,讓我們看看如何通過 Maven 插件在運行應用程序時傳遞參數。

然後,我們將學習如何在代碼中訪問這些參數。

2.1. Spring Boot 1.x

對於 Spring Boot 1.x,我們可以使用 -Drun.arguments 選項將參數傳遞給我們的應用程序。

mvn spring-boot:run -Drun.arguments=--customArgument=custom

我們還可以將多個參數傳遞給我們的應用程序:

mvn spring-boot:run -Drun.arguments=--spring.main.banner-mode=off,--customArgument=custom

請注意:

  • 參數應使用逗號分隔。
  • 每個參數應以 — 開頭。
  • 我們還可以傳遞配置屬性,例如 spring.main.banner-mode,如示例中所示。

2.2. Spring Boot 2.x

對於 Spring Boot 2.x,可以使用 <span style="font-style: italic;">-Dspring-boot.run.arguments</span > 參數傳遞啓動選項。

mvn spring-boot:run -Dspring-boot.run.arguments=--spring.main.banner-mode=off,--customArgument=custom

3. Gradle 命令參數

接下來,讓我們瞭解如何通過 Gradle 插件在運行應用程序時傳遞參數。

我們需要在 build.gradle 文件中配置 bootRun 任務:

bootRun {
    if (project.hasProperty('args')) {
        args project.args.split(',')
    }
}

現在我們可以傳遞命令行參數:

./gradlew bootRun --args=--spring.main.banner-mode=off,--customArgument=custom

4. 覆蓋系統屬性

除了傳遞自定義參數,我們還可以覆蓋系統屬性。

例如,這是我們的 application.properties 文件:

server.port=8081
spring.application.name=SampleApp

為了覆蓋 server.port 的值,我們需要按照以下方式傳遞新的值(適用於 Spring Boot 1.x):

mvn spring-boot:run -Drun.arguments=--server.port=8085

同樣,對於 Spring Boot 2.x:

mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=8085

請注意:

  • Spring Boot 會將命令行參數轉換為屬性,並將它們作為環境變量添加。
  • 我們可以使用簡短的命令行參數,例如 –port=8085,而不是 –server.port=8085,通過在我們的 application.properties 中使用佔位符來實現:
server.port=${port:8080}
  • 命令行參數優先於application.properties配置文件的值。
  • 如果需要,我們可以阻止應用程序將命令行參數轉換為屬性值。
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        application.setAddCommandLineProperties(false);
        application.run(args);
    }
}

5. 訪問命令行參數

讓我們看看如何從應用程序的 main() 方法中訪問命令行參數:

@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    public static void main(String[] args) {
        for(String arg:args) {
            System.out.println(arg);
        }
        SpringApplication.run(Application.class, args);
    }
}

這將打印我們從命令行傳遞給應用程序的所有參數,但我們也可以稍後在應用程序中使用它們。

6. 將命令行參數注入到 SpringBootTest

隨着 Spring Boot 2.2 的發佈,我們現在可以使用 @SpringBootTest 及其 args 屬性,在測試過程中注入命令行參數。

@SpringBootTest(args = "--spring.main.banner-mode=off")
public class ApplicationTest {

    @Test
    public void whenUsingSpringBootTestArgs_thenCommandLineArgSet(@Autowired Environment env) {
        Assertions.assertThat(env.getProperty("spring.main.banner-mode")).isEqualTo("off");
    }
}

7. 結論

在本文中,我們學習瞭如何使用 Maven 和 Gradle 將參數傳遞到我們的 Spring Boot 應用程序中。

我們還演示瞭如何從代碼中訪問這些參數,以便配置應用程序。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.