使用Spring Boot从命令行接收输入

时间:2019-05-29 10:36:05

标签: java spring spring-boot

因此,我有一个非常小的Spring Boot命令行应用程序(没有嵌入式tomcat服务器或任何使其成为Web应用程序的东西),只有一个类,我尝试使用{{ 1}}来自java.util的类,以读取用户的输入。这根本不起作用。我以为这是Spring Boot中非常基本的东西,但是我在S.O或教程上的所有搜索都没有结果。最好的方法是什么?还是Spring Boot不能满足我的需求?

这是我的课程:

Scanner

抛出的异常是:

package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Scanner;

@SpringBootApplication
public class MyApplication implements CommandLineRunner {

    private static Logger LOG = LoggerFactory
        .getLogger(MyApplication.class);

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("EXECUTING : command line runner");

        Scanner in = new Scanner(System.in);

        System.out.println("What is your name?");
        String name = in.next();
        System.out.println("Hello " + name + " welcome to spring boot" );
    }
}

4 个答案:

答案 0 :(得分:2)

  

还是Spring Boot不能满足我的需求?

你是对的。

Spring Boot应用程序是一个服务器程序(与其他.war一样),并且在嵌入式Tomcat中运行。这里可以使用哪种扫描仪?

如果要与之交互-您应该创建REST控制器并通过端点发送/接收数据。

答案 1 :(得分:2)

Spring Boot不适用于任何通用用途。它有特定的用途。我们不应该总是考虑如何将Spring Boot用于任何类型的需求。我知道Spring Boot已变得非常流行。对于您的问题,如果要创建交互式应用程序/程序,则必须以简单的方式进行。我只在下面的代码段中提供

public class Interactive
{

  public static void main (String[] args)
  {
    // create a scanner so we can read the command-line input
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter your name ? ");
    String username = scanner.next();
    System.out.print("Enter your age ? ");
    int age = scanner.nextInt();

    //Print all name, age etc
  }

}

希望这可能是您的要求。同样,Spring Boot应用程序不能说是真正意义上的交互式。有很多解释。 Spring Boot适用于客户端服务器架构。

答案 2 :(得分:1)

我遵循以下方法,

@SpringBootApplication
public class Test {
    public static void main(String[] args) {
        SpringApplication.run(Test.class, args);
    }
}

@Component
public class MyRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Enter word!");
        Scanner scanner = new Scanner(System.in);
        String line = scanner.nextLine();
        System.out.println(line);
     }
}

对我来说效果很好,您也可以在主类中组合命令行侦听器。

答案 3 :(得分:0)

因此,我找到了一种方法,可以通过试用普通的gradle应用程序(而不是spring boot)来使其工作。我遇到了同样的问题,解决方案是在我的build.gradle文件中添加一行以连接默认的stdin

在普通的Java gradle应用程序中:

run {
    standardInput = System.in
}

但是在Spring Boot应用程序中,我添加了以下行:

bootRun {
    standardInput = System.in
}

结果证明Spring Boot毕竟可以处理命令行应用程序。