本篇文章将介绍如何使用springboot搭建一个非web项目,即控制台项目。
springboot是一个快速构建微服务的框架,几乎是傻瓜式的一键生成项目。我们知道用它实现web服务很方便,有时我们想要实现非web项目,任务跑完之后就结束运行。经过查阅官方文档,springboot也提供了该方法。下面进入正题。
- 引入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>
划重点:不能引入spring-boot-starter-web,否则springboot将会以web方式加载项目。同时,如果项目中有其他依赖了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实现接口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.");
}
}
仅需要这两步,项目已可以正常运行。下面说下如何打包。同样,重点在于exculde掉web相关依赖。
<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>
网友评论