Spring Boot Run code when the application starts
By:Roy.LiuLast updated:2019-08-11
In Spring Boot, we can create a CommandLineRunner bean to run code when the application is fully started.
StartBookApplication.java
package com.mkyong; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; @SpringBootApplication public class StartBookApplication { public static void main(String[] args) { SpringApplication.run(StartBookApplication.class, args); // Injects a repository bean @Bean CommandLineRunner initDatabase(BookRepository repository) { return args -> { repository.save( new Book("A Guide to the Bodhisattva Way of Life") ); }; // Injects a ApplicationContext @Bean CommandLineRunner initPrint(ApplicationContext ctx) { return args -> { System.out.println("All beans loaded by Spring Boot:\n"); List<String> beans = Arrays.stream(ctx.getBeanDefinitionNames()) .sorted(Comparator.naturalOrder()) .collect(Collectors.toList()); beans.forEach(x -> System.out.println(x)); }; // Injects nothing @Bean CommandLineRunner initPrintOneLine() { return args -> { System.out.println("Hello World Spring Boot!"); };
P.S Tested with Spring Boot 2
From:一号门
Previous:Spring Boot YAML example
COMMENTS