第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定

用 SpringBoot 實(shí)現(xiàn)一個(gè)命令行應(yīng)用

標(biāo)簽:
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


點(diǎn)擊查看更多內(nèi)容
TA 點(diǎn)贊

若覺得本文不錯(cuò),就分享一下吧!

評(píng)論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 評(píng)論
  • 收藏
  • 共同學(xué)習(xí),寫下你的評(píng)論
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊有機(jī)會(huì)得

100積分直接送

付費(fèi)專欄免費(fèi)學(xué)

大額優(yōu)惠券免費(fèi)領(lǐng)

立即參與 放棄機(jī)會(huì)
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)

舉報(bào)

0/150
提交
取消