Writing console program based on Spring Boot

Keywords: Programming Spring Java REST

Of course, most Spring Boot programs in the world are Web programs. If you look away from the Web and zoom into the whole program world, you will surely see that the console program is a more basic and extensive kind of program.

Console programs written in Java can also enjoy the benefits of Spring Boot.

To develop a console program based on Spring Boot, you need to implement an interface

@FunctionalInterface
public interface CommandLineRunner {
    void run(String... args) throws Exception;
}

For example:

class DartApplication implements CommandLineRunner {
    @Override
    public void run(String... args) {
        System.out.println("The actual entry to the program is here.");
    }
}

Add @ SpringBootApplication annotation to this class, and then write a class with main function.

@SpringBootApplication
class DartApplication implements CommandLineRunner {
    @Override
    public void run(String... args) {
        System.out.println("The actual entry to the program is here.");
    }
}

public class App {
    public static void main(String[] args) {
        SpringApplication.run(DartApplication.class, args);
    }
}

Of course, you can also put the main function in DartApplication

@SpringBootApplication
public class DartApplication implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(DartApplication.class, args);
    }

    @Override
    public void run(String... args) {
        System.out.println("The actual entry to the program is here.");
    }
}

The annotation provided by Spring and the convenient starter provided by Spring Boot can still be used here.

For example, automatic assembly:

@Component
class Diablo {
    void firenova() {
        System.out.println("Release the new fire");
    }
}

@SpringBootApplication
public class DartApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(DartApplication.class, args);
    }

    @Autowired
    public DartApplication(Diablo diablo) {
        this.diablo = diablo;
    }

    private final Diablo diablo;

    @Override
    public void run(String... args) {
        this.diablo.firenova();
    }
}

In a word, to develop a console program based on Spring Boot is to implement an interface, and the rest is still OK.

Posted by Blu_Smurf on Sun, 08 Dec 2019 15:50:34 -0800