Home > OS >  How does CommandLineRunner works in Spring boot
How does CommandLineRunner works in Spring boot

Time:11-07

I found the below code somewhere

@SpringBootApplication
public class UsingCommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(UsingCommandLineRunner.class);
    }

    @Bean
    public CommandLineRunner demo(){
        return (args) -> {
             // do something
        };
    }
}

How does this even working?

Who is invoking demo?

@SpringBootApplication
public class UsingCommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(UsingCommandLineRunner.class);

        System.out.println("Args inside main()");
        for(int i=0; i<args.length; i  ){
            System.out.println(args[i]);
        }
    }

    @Bean
    public CommandLineRunner demo(){
        return (args) -> {
            System.out.println("Args inside demo()");
            for(int i=0; i<args.length; i  ){
                System.out.println(args[i]);
            }
            System.out.println("Using CommandLineRunner");
        };
    }
}

Upon running the above code, the below is what got printed.

Args inside demo()
Using CommandLineRunner
Args inside main()
userName=Rahul_Kumar

Why command line arguments are not inside args inside demo?

CodePudding user response:

you should run this app use SpringApplication.run(UsingCommandLineRunner.class,args);

CodePudding user response:

First notice that your demo method only returns a lambda, it doesn't call run on anything. That lambda gets typed as a CommandLineRunner thanks to target typing, and it does have a run method that takes the command line arguments. So your code is configuring a CommandLineRunner, Spring will see the @Bean annotation and will know to use the method to create the bean and put it in the application context during startup.

The command line arguments are read by the SpringApplication run method, which (after doing a lot of preparation) calls another method in the same class called callRunners. The callRunners method retrieves all the commandLineRunners from the application context and calls run on each of them, passing in the arguments.

See the source code: https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java

As to why it's like this: the Runners are Spring beans, the developers want to be able to have multiple runners, and have them run in an orderly fashion after startup is completed. If the code configuring the Runner needs to know the args passed in, it still doesn't need the args array directly, the args get converted into Spring properties.

  • Related