前言
前面我們介紹的 SpringBoot 都是在將如何實現(xiàn)一個獨立運行的 web 應用。不過在實際應用場景中卢鹦,很多時候我們也需要使用獨立運行的程序來實現(xiàn)一些任務。那么在 SpringBoot 中如何來實現(xiàn)這樣一個命令行模式的應用呢绳锅。其實也很簡單飒焦,只要讓 SpringBoot 的啟動類實現(xiàn)一個 org.springframework.boot.CommandLineRunner 接口就可以了那槽。
操作步驟
首先按照標準的方式在 IDEA 中建立一個標準的 springboot 的工程悼沿。在這個 SpringBoot 工程的啟動類上實現(xiàn) org.springframework.boot.CommandLineRunner 接口的 run 方法即可。如下所示
package com.yanggaochao.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CommandDemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpiderDemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println("sldkjfslkdjf");
}
}
這樣的 SpringBoot 的執(zhí)行方式就不再是一個獨立運行的 web 的方式骚灸,而是一個命令行的方式糟趾。那么他和非 SpringBoot 命令行方式的不同在哪里呢?主要是他能夠利用 SpringBoot 的其他所有功能。例如他可以自動裝配工程中的其他服務類义郑,并進行調(diào)用蝶柿。例如,我們有一個服務如下非驮。
package com.yanggaochao.demo;
import org.springframework.stereotype.Service;
/**
* 服務樣例
*
* @author : 楊高超
* @since : 2018-11-19
*/
@Service
public class HelloService {
public String sayHello(String name) {
return "Hello," + name;
}
}
那么交汤,我們在 SpringBoot 的命令行程序中就可以調(diào)用他了。原來的啟動類代碼改變?yōu)?/p>
package com.yanggaochao.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CommandDemoApplication implements CommandLineRunner {
private final HelloService helloService;
public CommandDemoApplication(HelloService helloService) {
this.helloService = helloService;
}
public static void main(String[] args) {
SpringApplication.run(SpiderDemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
if (args.length == 0) {
System.out.println(helloService.sayHello(args[0]));
} else {
System.out.println(helloService.sayHello("nobody"));
}
}
}
這樣劫笙,我們?nèi)绻斎胍粋€參數(shù) “world” 的時候執(zhí)行這個命令行程序芙扎,則會輸出 “Hello,world” 。如果不輸入?yún)?shù)或者輸入不止一個參數(shù)邀摆,則會輸出 “Hello,nobody”