基于spring boot编写控制台命令行程序

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程序的启动运行方法一样。

示例代码下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿20

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值