如何在Spring Boot中获取命令行参数? [英] How to get command Line arguments in spring boot?

查看:101
本文介绍了如何在Spring Boot中获取命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@SpringBootApplication
public class CommandLinetoolApplication {

@Value("${person.name}")
private String name;

public static void main(String... argv) {
    SpringApplication.run(CommandLinetoolApplication.class, argv);
 }  
}

我正在使用eclipse,因此将运行配置设置为
-Dspring-boot.run.arguments =-person.name =名字

I am using eclipse so setting run configuration as
-Dspring-boot.run.arguments=--person.name=firstName

但是在运行我的应用程序时,出现异常无法解析值"$ {person.name}"中的占位符'person.name'"

But when run my application,I am getting exception as "Could not resolve placeholder 'person.name' in value "${person.name}"

推荐答案

此代码工作正常(Spring Boot 2.1.4):

This code works just fine (Spring Boot 2.1.4):

@SpringBootApplication
public class DemoApplication implements ApplicationRunner
{

    @Value("${person.name}")
    private String name;

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

    @Override
    public void run( ApplicationArguments args ) throws Exception
    {
        System.out.println( "Name: " + name );
    }
}

命令行:

mvn spring-boot:run -Dspring-boot.run.arguments=--person.name=Test

输出:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-04-28 22:51:09.741  INFO 73751 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication on xxx-MacBook-Pro.local with PID 73751 (/Users/strelok/code/demo-sb/target/classes started by strelok in /Users/strelok/code/demo-sb)
2019-04-28 22:51:09.745  INFO 73751 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2019-04-28 22:51:10.943  INFO 73751 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 16.746 seconds (JVM running for 23.386)
Name: Test

这篇关于如何在Spring Boot中获取命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆