Using Spring Boot CommandLineRunner

A quick post on a cool Spring Boot Interface called CommandLineRunner. With CommandLineRunner you can perform tasks after all Spring Beans are created and the Application Context has been created.

From the Spring Boot Documentation:

If you want access to the raw command line arguments, or you need to run some specific code once the SpringApplication has started you can implement the CommandLineRunner interface. The run(String…​ args) method will be called on all Spring beans implementing this interface. You can additionally implement the @Ordered interface if several CommandLineRunner beans are defined that must be called in a specific order.

Here’s a simple sample from NixMash Spring.

@Component
public class ApplicationLoader implements CommandLineRunner {

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

    @Override
    public void run(String... strings) throws Exception {
        StringBuilder sb = new StringBuilder();
        for (String option : strings) {
            sb.append(" ").append(option);
        }
        sb = sb.length() == 0 ? sb.append("No Options Specified") : sb;
        logger.info(String.format("WAR launched with following options: %s", sb.toString()));
    }
}

It’s a superfluous little function that simply logs the command line arguments used when launching the WAR file at the command line.

What’s interesting is that the ApplicationLoader class above is in the NixMash Spring JPA RootContext Module, but @SpringBootApplication in the MVC WebContext Module will pick up the class because we added the @Component annotation and implement the CommandLineRunner Interface.

Here is sample output when firing up the web application from the command line with

$ java -jar nixmashSpring.war --spring.one=one --spring.two=two

A small screenshot display, sorry, but you’ll see the “WAR launched with following options…” on the 3rd line.

You’ll typically want to do something more substantial with CommandLineRunner than what we’ve done here. You will also want to remember its JobLauncherCommandLineRunner implementation for running jobs in Spring Batch. Regardless, you’ll want to remember CommandLineRunner.