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.

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

References

About the Author

author image
mkyong
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.

Comments

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

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