CommandLineRunner and ApplicationRunner interfaces

Spring Boot provides two interfaces to run specific pieces of code when an application is fully started. These interfaces get called just before run() once SpringApplication completes.

  • CommandLineRunner interface provides access to application arguments as string array. Here’s the example :
@Component
public class CommandLineAppStartupRunner implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(CommandLineAppStartupRunner.class);
    @Override
    public void run(String...args) throws Exception {
        logger.info("Application started with command-line arguments: {} . \n To kill this application, press Ctrl + C.", Arrays.toString(args));
    }
}
  • ApplicationRunner wraps the raw application arguments and exposes the ApplicationArguments interface, which has many convenient methods to return all the arguments’ names, like getOptionNames() to return all the arguments’ names, getOptionValues() to return the argument value, and raw source arguments with method getSourceArgs(). Here’s the example :
@Component
public class AppStartupRunner implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(AppStartupRunner.class);
    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("Your application started with option names : {}", args.getOptionNames());
    }
}

These interfaces can be useful if a developer wants to execute some piece of code exactly before the application startup completes.

Developer can register as many application/command line runners as he wants. They just need to be registered as beans in the application context. Then, Spring will automatically pick them up. They can be ordered as well either by extending interface org.springframework.core.Ordered or via the @Order annotation.

Leave a Reply

Your email address will not be published. Required fields are marked *