Spring Boot – Run code when the application starts

In Spring Boot, we can create a CommandLineRunner bean to run code when the application is fully started.


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;

public class StartBookApplication {

    public static void main(String[] args) {
        SpringApplication.run(StartBookApplication.class, args);

	// Injects a repository bean
    CommandLineRunner initDatabase(BookRepository repository) {
        return args -> {

				new Book("A Guide to the Bodhisattva Way of Life")

	// Injects a ApplicationContext
    CommandLineRunner initPrint(ApplicationContext ctx) {
        return args -> {

            System.out.println("All beans loaded by Spring Boot:\n");

            List<String> beans = Arrays.stream(ctx.getBeanDefinitionNames())

            beans.forEach(x -> System.out.println(x));


	// Injects nothing
    CommandLineRunner initPrintOneLine() {
        return args -> {

            System.out.println("Hello World Spring Boot!");



P.S Tested with Spring Boot 2


About the Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.


1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Ahmed Salem Recent comment authors
newest oldest most voted
Ahmed Salem
Ahmed Salem

Good article, I think we can also use @PostConstract annotation if we need to run code in a component init