spring boot除了可以开发web程序以外,还可以开发控制台程序。对于不需要提供web服务,只需要提供控制台命令行服务的程序,可以实现一个命令行接口的方式,提供控制台程序。
可以减少不必要的包依赖,减小最终的jar大小,也降低内存的占用。
1. pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.3.11.RELEASE</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-web</artifactId>-->
<!-- <version>2.3.11.RELEASE</version>-->
<!-- </dependency>-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.1.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
这里需要增加一个execution配置,不然打包不完整。
2. 主程序代码
package com.platform.console;
import com.platform.console.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConsoleApplication implements CommandLineRunner {
@Autowired
DemoService demoService;
public static void main(String[] args) {
SpringApplication.run(ConsoleApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
demoService.hello();
System.out.println("程序实际上的入口在这里。");
}
}
可以看到,主程序实现了一个控制台接口。
3. 服务代码
package com.platform.console.service;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
public void hello() throws InterruptedException {
while (true)
{
System.out.println("hello");
Thread.sleep(3000);
}
}
}
这里定义的服务,是
4. 打包后运行
java -jar spring-boot-console-1.0.jar
hello
hello
hello
hello
可以看到,启动运行方法,和web程序的启动运行方法一样。