在Spring Boot中启动应用程序时运行代码的方法

x33g5p2x  于2022-10-18 转载在 Spring  
字(1.9k)|赞(0)|评价(0)|浏览(598)

让我们学习如何在启动spring引导应用程序时运行一段代码。

使用CommandLineRunner或ApplicationRunner

您可以提供CommandLineRunner类型的Bean或ApplicationRunner接口。使用这种方法的好处是允许代码访问应用程序参数。

@Bean
CommandLineRunner commandLineRunner() {
  return new CommandLineRunner() {
    @Override
    public void run(String... args) throws Exception {
      log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
      log.info("These Lines will get printed on application startup");
      log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    }
  };
}
Code language: JavaScript (javascript)

@Bean
ApplicationRunner applicationRunner() {
  return new ApplicationRunner() {
    @Override
    public void run(ApplicationArguments args) throws Exception {
      log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
      log.info("These Lines will get printed on application startup too");
      log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    }
  };
}
Code language: PHP (php)

请注意,这些代码段之间的唯一区别是通过ApplicationArguments对象可以更好地控制参数。

使用事件侦听器在应用程序启动时运行代码

Springboot在其应用程序生命周期中会发出许多事件。因此,我们可以为ApplicationStartedEvent或ContextRefreshedEvent定义侦听器,以了解何时运行代码。

@EventListener
public void executeOnStartup(ApplicationStartedEvent event) {
  log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
  log.info("Another way to run something on application startup with event {}", event);
  log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
Code language: CSS (css)

最重要的是,您可以通过event参数访问应用程序上下文。
要在上下文完成但应用程序启动之前运行代码,则应使用ContextRefreshedEvent

通过SmartInitializingSingleton

最后一种可能更简单的方法是定义SmartInitializingSingleton的实现。在所有单例bean创建完成后,Springboot将查找此回调bean。

@Bean
SmartInitializingSingleton smartInitializingSingleton(ApplicationContext context) {
  return () -> {
    log.info("This runs on startup too... {}", context);
  };
}
Code language: JavaScript (javascript)

当您有一个简单的场景,并且不想包含除springbeans jar之外的任何依赖项时,这种方法非常有用。
此外,此实现在某种程度上与ContextRefreshedEvent的侦听器同义。

您可以在this gist的spring-boot应用程序中找到所有这些在启动时运行代码的示例。

相关文章

微信公众号

最新文章

更多