【问题标题】:Calling Spring Boot method from terminal从终端调用 Spring Boot 方法
【发布时间】:2020-02-22 13:09:01
【问题描述】:

我正在研究如何从终端调用方法。

@Component
public class ApplicationAdapter implements CommandLineRunner {

    @Autowired
    private IApplicationPort iApplicationPort;

    @Override
    public void run(String... args) throws Exception {
        iApplicationPort.getAll();
        iApplicationPort.deleteStudentById((long) 1);
    }
}

这是主类

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

我希望从终端调用 2 个方法:getAll();deleteStudentById((long) 1);。我该怎么做?

【问题讨论】:

    标签: java spring-boot command-line method-call mainclass


    【解决方案1】:

    首先,您不需要实例化 ApplicationAdapter。由于 @Component 注释,这将由 Spring 完成:

    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
            // new ApplicationAdapter(); REMOVE
        }
    }
    

    然后您可以使用启动应用程序时传递的参数:

    @Component
    public class ApplicationAdapter implements CommandLineRunner {
    
        @Autowired
        private IApplicationPort iApplicationPort;
    
        @Override
        public void run(String... args) throws Exception {
            if (args[0].equals("all")) {
                iApplicationPort.getAll();
            } else if (args[0].equals("delete"))
                iApplicationPort.deleteStudentById(Long.parseLong(args[1]));
            } 
        }
    }
    

    然后你可以像这样启动你的应用程序:

    java -jar yourApp.jar all
    
    java -jar yourApp.jar delete 1
    

    【讨论】:

    • 如果我的回答对您有帮助,请接受回答并点赞。谢谢
    • 谢谢。我确定这不是正确的方向,但我得到了Caused by: java.lang.ArrayIndexOutOfBoundsException: 0 at org.package.ApplicationAdapter.run(ApplicationAdapter.java:19) ~[classes/:na] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:781) [spring-boot-2.1.9.RELEASE.jar:2.1.9.RELEASE] ... 10 common frames omitted
    • 如何调用程序?
    • 当我尝试在 IntelliJ 中启动程序时它失败了
    猜你喜欢
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 2017-01-21
    • 2019-09-16
    • 1970-01-01
    相关资源
    最近更新 更多