Want to improve as a dev?

I send a short email every workday about Spring topics, API development and improving as a dev.

I understand and agree to the privacy policy

Commandline Applications with Spring Boot

08.02.2018 by Jens in Newsletter | Spring Boot

Spring Boot is not only for server applications. Did you know you can write command line apps too?

We can do so in two simple steps.

First, we must code a class implementing the CommandLineRunner interface. It has just one method run which is executed by Spring Boot once. It contains our logic what to do.

Second, we must add that class to the Spring Context as any other regular Spring bean.

Example:

@SpringBootApplication
public class CmdRunnerApplication implements CommandLineRunner {

    public static void main(String[] args) {
        new SpringApplicationBuilder(CmdRunnerApplication.class).web(false).run(args);
    }

    @Override
    public void run(String... arg0) throws Exception {
        System.out.println("Run");

    }
}

The CommandLineRunner is executed on startup by Spring Boot, and it is even executed when we build a web app and start a Tomcat. Besides writing command line apps, we could use it also to run code at startup once.

The mechanism also supports multiple CommandLineRunner at the same time. They are all executed in order; usually, as they were picked up by the Spring context. With setting the @Order annotation on our CommandLineRunner implementation, we can override that.


comments powered by Disqus