Saturday, November 2, 2019

Spring Boot: CommandLineRunner and ApplicationRunner

Do you want to run some code before Spring boot application starts, however after ApplicationContext is loaded ?

If Answer is Yes, you have 2 interfaces at your service - CommandLineRunner and ApplicationRunner.

Both have single method called run(...), one accepts String[] as argument, the other accepts 'ApplicationArguments' which is nothing but a nice wrapper around supplied args.

you can read more about it here.

@Component
@Order(1)
public class SampleCmdRunner implements CommandLineRunner {
    @Override
    public void run(String[] args) {
        System.out.println("Executing the command line runner);
    }
}
@Component @Order(2) public class SampleAppRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) { System.out.println("Executing SampleAppRunner");
} }


In case of multiple CommandRunner and ApplicationRunner we can order them using @Order annotation.

No comments: