本篇文章將介紹如何使用springboot搭建一個非web項(xiàng)目显拜,即控制臺項(xiàng)目颇蜡。
springboot是一個快速構(gòu)建微服務(wù)的框架遇西,幾乎是傻瓜式的一鍵生成項(xiàng)目能颁。我們知道用它實(shí)現(xiàn)web服務(wù)很方便哼绑,有時我們想要實(shí)現(xiàn)非web項(xiàng)目岩馍,任務(wù)跑完之后就結(jié)束運(yùn)行。經(jīng)過查閱官方文檔抖韩,springboot也提供了該方法蛀恩。下面進(jìn)入正題。
- 引入springboot包
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
劃重點(diǎn):不能引入spring-boot-starter-web茂浮,否則springboot將會以web方式加載項(xiàng)目双谆。同時,如果項(xiàng)目中有其他依賴了spring-boot-starter-web席揽,必須exclude掉顽馋,像下面這樣。
<dependency>
<groupId>com.xxxx.xxx</groupId>
<artifactId>xxxx</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</exclusion>
</exclusions>
</dependency>
- Application.java實(shí)現(xiàn)接口CommandLineRunner
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EntityScan(basePackages = { "com.xxx.xxx" })
@ComponentScan(basePackages = { "com.xxx.xxx" })
public class App implements CommandLineRunner {
public static void main(String[] args) {
System.out.println("Hello Springboot!");
SpringApplication.run(App.class, args);
}
public void run(String... args) throws Exception {
System.out.println("This is console line.");
}
}
僅需要這兩步幌羞,項(xiàng)目已可以正常運(yùn)行寸谜。下面說下如何打包。同樣属桦,重點(diǎn)在于exculde掉web相關(guān)依賴熊痴。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludeArtifactIds>tomcat*</excludeArtifactIds>
<excludeArtifactIds>spring-web</excludeArtifactIds>
<excludeGroupIds>io.springfox</excludeGroupIds>
<excludes>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</exclude>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>