前言
前面我們介紹的 SpringBoot 都是在將如何實現一個獨立運行的 web 應用。不過在實際應用場景中,很多時候我們也需要使用獨立運行的程序來實現一些任務。那麼在 SpringBoot 中如何來實現這樣一個命令行模式的應用呢。其實也很簡單,只要讓 SpringBoot 的啓動類實現一個 org.springframework.boot.CommandLineRunner 接口就可以了。
操作步驟
首先按照標準的方式在 IDEA 中建立一個標準的 springboot 的工程。在這個 SpringBoot 工程的啓動類上實現 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 的執行方式就不再是一個獨立運行的 web 的方式,而是一個命令行的方式。那麼他和非 SpringBoot 命令行方式的不同在哪裏呢?主要是他能夠利用 SpringBoot 的其他所有功能。例如他可以自動裝配工程中的其他服務類,並進行調用。例如,我們有一個服務如下。
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 的命令行程序中就可以調用他了。原來的啓動類代碼改變爲
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"));
}
}
}
這樣,我們如果輸入一個參數 “world” 的時候執行這個命令行程序,則會輸出 “Hello,world” 。如果不輸入參數或者輸入不止一個參數,則會輸出 “Hello,nobody”