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

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

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

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

  1. import org.springframework.boot.CommandLineRunner;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication public DemoApplication implements CommandLineRunner {
  5. public void run(String...args) {
  6. // This will run after the SpringApplication.run(..)
  7. // Do something...
  8. }
  9. public static void main(String[] args) throws Exception {
  10. SpringApplication.run(MyApplication.class, args);
  11. }
  12. }

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

  1. @Bean public CommandLineRunner runner() {
  2. return new CommandLineRunner() {
  3. public void run(String...args) {
  4. //Run some process here
  5. }
  6. };
  7. }

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

  1. @Bean public CommandLineRunner runner(Repository repo) {
  2. return args -> {
  3. //Run some process here
  4. };
  5. }

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

  1. @Bean InitializingBean saveData(Repository repo) {
  2. return () -> {
  3. //Do some DB inserts
  4. };
  5. }

相关文章

最新文章

更多