美文网首页Spring-Boot
用 SpringBoot 实现一个命令行应用

用 SpringBoot 实现一个命令行应用

作者: 阿土伯已经不是我 | 来源:发表于2018-11-19 09:06 被阅读8次

    前言

    前面我们介绍的 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;
    
    @SpringBootApplication
    public 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
     */
    @Service
    public 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;
    
    @SpringBootApplication
    public 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”

    相关文章

      网友评论

        本文标题:用 SpringBoot 实现一个命令行应用

        本文链接:https://www.haomeiwen.com/subject/yaqkyftx.html