Lets say you need to write a command line Java Application using Spring Boot ... how do you achieve same ?
What is the CommandLineRunner Interface ?
Spring Boot provides two interfaces, CommandLineRunner and ApplicationRunner, to run specific pieces of code when an application is fully started. These interfaces get called just before run() once SpringApplication completes.
Both interfaces work in the same way and offer a single run method which will be called just before SpringApplication.run(…) completes.
You can have as many runners as you want , Just use @Order to manage execution order
import org.springframework.boot.CommandLineRunner; @SpringBootApplication public class SpringBootConsoleApplication implements CommandLineRunner { public static void main(String[] args) throws Exception { SpringApplication.run(SpringBootConsoleApplication.class, args); } //access command line arguments @Override public void run(String... args) throws Exception { //do something } }
What is the CommandLineRunner Interface ?
Spring Boot provides two interfaces, CommandLineRunner and ApplicationRunner, to run specific pieces of code when an application is fully started. These interfaces get called just before run() once SpringApplication completes.
Both interfaces work in the same way and offer a single run method which will be called just before SpringApplication.run(…) completes.
@Component @Order(1) public class AppStartupRunner implements ApplicationRunner { private static final Logger logger = LoggerFactory.getLogger(AppStartupRunner.class); @Override public void run(ApplicationArguments args) throws Exception { Set<String> argSet = args.getOptionNames(); logger.info("Your application started with option names : {}", argSet); } }
You can have as many runners as you want , Just use @Order to manage execution order
@Component @Order(2) 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)); } }
No comments:
Post a Comment