Is it possible to use Spring to create a console application?

Viewed 3167

Currently researching this topic. Is it possible to use the benefits of Spring to form a Console application? I mean, with scopes, autowiring and etc(found a bunch of examples of a basic "Set the context, init and go", but nothing more)?

Can't find any tutorials or helpful information on this topic.

4 Answers

CommandLineRunner example. If you run this Spring Boot, the run method will be the entry point.

package com.mkyong;

import com.mkyong.service.HelloMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import static java.lang.System.exit;

@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {

    @Autowired
    private HelloMessageService helloService;

    public static void main(String[] args) throws Exception {

        //disabled banner, don't want to see the spring logo
        SpringApplication app = new SpringApplication(SpringBootConsoleApplication.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);

    }

    // Put your logic here.
    @Override
    public void run(String... args) throws Exception {

        if (args.length > 0) {
            System.out.println(helloService.getMessage(args[0].toString()));
        } else {
            System.out.println(helloService.getMessage());
        }

        exit(0);
    }
}

Details

Spring is a framework which offers the dependency injection mechanism. It also supports segregation of service layer, web layer, and business layer but I believe that this is not what you want.

So the answer is yes. You can utilize the dependency injection service that provides in order to create a console application without facing any problems. Of course, the MVC model that offers is actually useless for you.

Related