引导 Spring Boot 应用程序的 4 种方法

x33g5p2x  于2022-10-05 转载在 Bootstrap  
字(1.1k)|赞(0)|评价(0)|浏览(271)

有几种方法可以引导 Spring Boot 独立应用程序。一种方法是实现 org.springframework.boot.CommandLineRunner 接口并实现 run(String... args) 方法。

当您想要执行作业或服务时,这很有用,例如发送有关应用程序的通知或执行 SQL 语句以在应用程序运行之前更新某些行。这是一个例子:

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication public DemoApplication implements CommandLineRunner {
  public void run(String...args) {
    // This will run after the SpringApplication.run(..)    
    // Do something...    
  }
  public static void main(String[] args) throws Exception {
    SpringApplication.run(MyApplication.class, args);
  }
}

以下代码向您展示了如何通过使用 @Bean 注释方法来将 CommandLineRunner 接口用作 Bean:

@Bean public CommandLineRunner runner() {
  return new CommandLineRunner() {
    public void run(String...args) {
      //Run some process here      
    }

  };

}

或者,如果您使用的是 Java 8,您可以像这样使用 lambdas 功能:

@Bean public CommandLineRunner runner(Repository repo) {
  return args -> {
    //Run some process here    
  };
}

以下代码向您展示了如何使用 Java 8 lambda 来使用 CommandLineRunner 接口。在这种情况下,方法的参数是一个 Repository ,它通常对执行一些数据库任务很有用。
也许您想知道如果您需要在 CommandLineRunner 之前运行一些代码,您需要做什么。您可以通过返回 InitializingBean 接口来做到这一点。

@Bean InitializingBean saveData(Repository repo) {
  return () -> {
    //Do some DB inserts 
  };
}

相关文章

微信公众号

最新文章

更多