Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are different ways to execute code once Spring Boot has started:

  1. Using CommandLineRunner interface: SpringApplication.run method accepts a vararg of command line arguments which can execute one or more implementations of CommandLineRunner interface.
@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        // Your code here
    }
}
  1. Using ApplicationRunner interface: Like CommandLineRunner, you can also implement ApplicationRunner interface to run code once Spring Boot application has started.
@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // Your code here
    }
}
  1. Using @PostConstruct annotation: You can annotate a method with @PostConstruct annotation to execute code once Spring Boot application has started and all beans have been initialized.
@Component
public class MyComponent {
    @PostConstruct
    public void init() {
        // Your code here
    }
}