Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get command Line arguments in spring boot?

@SpringBootApplication
public class CommandLinetoolApplication {

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

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

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

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

like image 364
Dhanraj Avatar asked Apr 26 '19 13:04

Dhanraj


People also ask

How do I get command line arguments?

Command-line arguments are given after the name of the program in command-line shell of Operating Systems. To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments.

Where is the command line argument?

What are Command Line Arguments in C? Command line arguments are nothing but simply arguments that are specified after the name of the program in the system's command line, and these argument values are passed on to your program during program execution.

How do you get the first command line argument?

argv[1] is the first command-line argument. The last argument from the command line is argv[argc - 1] , and argv[argc] is always NULL. For information on how to suppress command-line processing, see Customize C++ command-line processing. By convention, argv[0] is the filename of the program.


3 Answers

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 );
    }
}

Command line:

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

The output:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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
like image 54
Strelok Avatar answered Nov 01 '22 02:11

Strelok


You need to change your eclipse VM arguments as -Dperson.name=dhanraj

One more thing is there is no use to add private String name; in main class. Because main method is static method, so you need to create object to access name variable and ultimately new object gives you null value not the value you set dhanraj.

So Use this variable in Controller or Service part.

like image 27
GnanaJeyam Avatar answered Nov 01 '22 02:11

GnanaJeyam


You need to add a configuration property person.name=firstName in your application.properties

OR

Implement interface ApplicationRunner and override its run method(Correct way to read command line argument)

Example:

@SpringBootApplication
public class Application implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String... args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("Application started with command-line arguments: {}", Arrays.toString(args.getSourceArgs()));
        logger.info("NonOptionArgs: {}", args.getNonOptionArgs());
        logger.info("OptionNames: {}", args.getOptionNames());

        for (String name : args.getOptionNames()){
            logger.info("arg-" + name + "=" + args.getOptionValues(name));
        }

        boolean containsOption = args.containsOption("person.name");
        logger.info("Contains person.name: " + containsOption);
    }
}
like image 7
abj1305 Avatar answered Nov 01 '22 04:11

abj1305