命令行调用springboot服务_用 SpringBoot 实现一个命令行应用

前言

前面我们介绍的 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;@SpringBootApplicationpublic 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

*/@Servicepublic 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;@SpringBootApplicationpublic 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”

作者:高超杨

链接:https://www.jianshu.com/p/0bb00b8168af

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值