【问题标题】:What's the best way to Invoke a service on spring-boot start up?在 spring-boot 启动时调用服务的最佳方法是什么?
【发布时间】:2016-06-03 19:46:57
【问题描述】:

我有一个 Spring Boot 应用程序,我需要在启动时调用一个服务(一个休息端点)。

【问题讨论】:

    标签: java spring spring-boot spring-ioc


    【解决方案1】:

    CommandLineRunner

    @Component
    public class MyBean implements CommandLineRunner {
    
        public void run(String... args) {
            // Do something...
        }
    
    }
    

    您可以使用这个方便的界面在应用程序启动时执行任何您喜欢的任务。

    要调用 REST 端点,您可以使用 RestTemplate

    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject("http://www.example.com/api/resource", String.class);
    

    如果您使用与 JSON 响应匹配的字段构建 POJO,RestTemplate 将在 Jackson 的帮助下自动映射它们。有关详细信息,请参阅文档。

    【讨论】:

      【解决方案2】:

      我建议看一下@PostConstruct 注释。

      【讨论】:

        【解决方案3】:

        我会使用和实现ApplicationRunner

        【讨论】:

          【解决方案4】:

          您还可以将您的应用程序挂接到 ApplicationReadyEvent 或 Spring 触发的其他事件:

          http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-spring-application.html#boot-features-application-events-and-listeners

          【讨论】:

            猜你喜欢
            • 2015-12-05
            • 2018-12-13
            • 2022-09-28
            • 1970-01-01
            • 2016-01-04
            • 2021-11-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多