This Java tutorial demonstrates how to run code after spring boot application startup.
There are several ways using which we can execute code or logic right after starting of a spring boot application. For example, loading initial data into the database after application has started.
This tutorial shows one way that can be used to run your code right after the Spring application context has been instantiated with example using CommandLineRunner.
In a configuration class, declare a bean of type CommandLineRunner
1 |
@Configuration<br>public class AppConfig { <br> <br> @Bean<br> CommandLineRunner initDatabase() {<br> <br> return args -> {<br> <br> // insert some sample records upon startup…<br> <br> };<br> }<br>} |
Alternatively, you can create a @Component class that implements CommandLineRunner and override the run() method
1 2 3 4 5 6 7 8 9 10 11 |
@Component public class LoadDatabase implements CommandLineRunner { @Override public void run(String... args) throws Exception { // insert some sample records upon startup… } } |