登录
首页 >  文章 >  java教程

弹簧 - :命令行 - arguments-overview

时间:2025-02-01 13:07:10 247浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《弹簧 - :命令行 - arguments-overview》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

弹簧 - :命令行 -  arguments-overview

Spring Boot 应用的强大之处在于其灵活的运行时配置能力,而命令行参数正是实现这一能力的关键。本文将深入探讨如何在 Spring Boot 中使用命令行参数,覆盖默认设置或添加自定义参数,无需修改代码。

一、传递命令行参数

向 Spring Boot 应用传递命令行参数的方法取决于你的运行方式:

  • 可执行 JAR 包: 运行打包后的 JAR 文件时,直接在 JAR 文件名后添加参数:
java -jar myapp.jar --server.port=8081 --custom.argument=value
  • Maven 插件: 使用 Spring Boot Maven 插件时,利用 -Dspring-boot.run.arguments 属性传递参数:
mvn spring-boot:run -Dspring-boot.run.arguments="--server.port=8081,--custom.argument=value"
  • Gradle 插件:build.gradle 文件中配置 bootRun 任务,然后运行:
./gradlew bootRun --args="--server.port=8081,--custom.argument=value"

二、在应用代码中访问命令行参数

Spring Boot 提供两种接口来访问命令行参数:

  • CommandLineRunner 接口: 此接口允许你在 Spring 容器加载完成后执行代码,访问命令行参数:
@SpringBootApplication
public class MyApp implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        for (String arg : args) {
            System.out.println(arg);
        }
    }
}
  • ApplicationRunner 接口:CommandLineRunner 类似,但提供 ApplicationArguments 接口,用于更结构化的参数访问:
@SpringBootApplication
public class MyApp implements ApplicationRunner {

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (args.containsOption("custom.argument")) {
            System.out.println("Custom argument: " + args.getOptionValues("custom.argument"));
        }
    }
}

这两种方法都能处理选项参数(例如 --custom.argument=value)和非选项参数。

三、覆盖应用属性

命令行参数可以覆盖 application.propertiesapplication.yml 文件中定义的属性。例如,修改服务器端口:

  • 命令行: java -jar myapp.jar --server.port=8081
  • Maven: mvn spring-boot:run -Dspring-boot.run.arguments="--server.port=8081"

命令行参数优先级最高,确保其覆盖其他配置。

四、禁用命令行属性转换

Spring Boot 默认将命令行参数转换为属性并添加到 Spring 环境中。如果需要禁用此行为,可以在主类中进行设置:

@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApp.class);
        app.setAddCommandLineProperties(false);
        app.run(args);
    }
}

这将阻止命令行参数添加到环境中。

(参考:Baeldung, Spring Boot 官方文档)

以上就是《弹簧 - :命令行 - arguments-overview》的详细内容,更多关于的资料请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>