Spring Boot应用参数访问指南

Spring Boot应用参数访问指南

在Spring Boot应用程序中,我们可以通过两种方式访问应用程序参数:

  1. 注入ApplicationArguments:ApplicationArguments提供了访问用于运行SpringApplication的参数。
  2. 使用@Value注解:Spring Boot会自动注册CommandLinePropertySource到Spring Environment中,这意味着我们无需额外配置即可使用@Value注解。

通过注入ApplicationArguments访问参数

首先,我们创建一个Spring Boot配置类并注入ApplicationArguments。然后,通过ApplicationArguments获取参数值。

@SpringBootConfiguration
public class ExampleMain {
    @Bean
    MyBean myBean() {
        return new MyBean();
    }

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(ExampleMain.class, args);
        MyBean myBean = context.getBean(MyBean.class);
        myBean.doSomething();
    }

    private static class MyBean {
        @Autowired
        ApplicationArguments appArgs;

        public void doSomething() {
            List<String> args = appArgs.getOptionValues("myArg");
            if (args.size() > 0) {
                System.out.printf("The value of application arg myArg: %s%n", args.get(0));
            }
        }
    }
}

使用Maven运行应用程序,并传递参数:

mvn -q spring-boot:run -DtheMainClass="com.logicbig.example.ExampleMain" -Drun.arguments="--myArg=myArgVal"

使用@Value注解访问参数

这种方式更为简洁,我们不需要添加CommandLinePropertySource到Environment对象中,并且我们的Bean将不受Spring特定API的限制。

@SpringBootConfiguration
public class ExampleMain2 {
    @Bean
    MyBean myBean() {
        return new MyBean();
    }

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(ExampleMain2.class, args);
        MyBean myBean = context.getBean(MyBean.class);
        myBean.doSomething();
    }

    private static class MyBean {
        @Value("${myArg}")
        private String myArgStr;

        public void doSomething() {
            System.out.printf("The value of application arg myArg: %s%n", myArgStr);
        }
    }
}

同样使用Maven运行应用程序,并传递参数:

mvn -q spring-boot:run -DtheMainClass="com.logicbig.example.ExampleMain2" -Drun.arguments="--myArg=myArgVal"

示例项目

依赖和使用的技术:

  • Spring Boot 1.5.3.RELEASE
  • 对应的Spring版本 4.3.8.RELEASE
  • spring-boot-starter:核心启动器,包括自动配置支持,日志记录和YAML。
  • JDK 1.8
  • Maven 3.3.9

通过以上两种方法,我们可以灵活地访问Spring Boot应用程序的参数,以满足不同的开发需求。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

t0_54coder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值