【问题标题】:can Spring boot be used in a "one shot" programSpring Boot 可以在“一次性”程序中使用吗
【发布时间】:2017-03-13 16:55:48
【问题描述】:

我不知道什么是合适的术语,但我所说的“一次性”程序是指从主函数开始到结束并退出的程序。

通常我会使用这样的样板:

AnnotationApplicationContext ac = new AnnotationApplicationContext("myConfigClass") 
MyBean myStuff = ac.getBean("myBean");
myStuff.doSomething();
ac.flush();
ac.close();

我仍然可以使用很多这样的 Spring 特性编程。但是,当我尝试 Spring boot 时,我只是这样做(请忽略语法错误,因为我在脑海中乱写了 sn-p) - 它认为它进一步简化了编程(行数更少,注释更少) :

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

但是,我注意到该程序在启动后会一直作为服务,直到被明确终止。

因此,我的问题是:Springboot 是否仅适用于 Spring MVC 之类的 Web 应用程序或 Webservice 样式的服务?它不适合简单的“一次性”程序吗?一个相关的问题是:嵌入式tomcat(或Jitty)是否总是在使用并运行SpringBootApplication时启动?

希望我能理解自己。有人可以帮忙吗?

【问题讨论】:

标签: java spring web-services spring-mvc spring-boot


【解决方案1】:

如果您使用 CLR (CommandLineRunner) 运行 Spring Boot 应用程序,则不需要服务器

@SpringBootApplication
public class App implements CommandLineRunner {

    @Autowired
    private MyBean myStuff;

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

    public void run(String... strings) throws Exception {
        myStuff.doSomething();
    }
}

【讨论】:

    猜你喜欢
    • 2017-08-31
    • 2019-02-21
    • 2018-05-02
    • 2018-08-28
    • 2017-12-13
    • 2015-07-09
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多