Ask Your Question
4

What is the way to execute code once Spring Boot has started?

asked 2021-11-02 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-11-25 01:00:00 +0000

plato gravatar image

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
    }
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-11-02 11:00:00 +0000

Seen: 13 times

Last updated: Nov 25 '22