java - Running code after Spring Boot starts

ID : 10420

viewed : 37

Tags : javaspringspring-bootjava

Top 5 Answer for java - Running code after Spring Boot starts

vote vote

99

It is as simple as this:

@EventListener(ApplicationReadyEvent.class) public void doSomethingAfterStartup() {     System.out.println("hello world, I have just started up"); } 

Tested on version 1.5.1.RELEASE

vote vote

82

Try:

@Configuration @EnableAutoConfiguration @ComponentScan public class Application extends SpringBootServletInitializer {      @SuppressWarnings("resource")     public static void main(final String[] args) {         ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);          context.getBean(Table.class).fillWithTestdata(); // <-- here     } } 
vote vote

72

Have you tried ApplicationReadyEvent?

@Component public class ApplicationStartup  implements ApplicationListener<ApplicationReadyEvent> {    /**    * This event is executed as late as conceivably possible to indicate that     * the application is ready to service requests.    */   @Override   public void onApplicationEvent(final ApplicationReadyEvent event) {      // here your code ...      return;   } } 

Code from: http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/

This is what the documentation mentions about the startup events:

...

Application events are sent in the following order, as your application runs:

An ApplicationStartedEvent is sent at the start of a run, but before any processing except the registration of listeners and initializers.

An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known, but before the context is created.

An ApplicationPreparedEvent is sent just before the refresh is started, but after bean definitions have been loaded.

An ApplicationReadyEvent is sent after the refresh and any related callbacks have been processed to indicate the application is ready to service requests.

An ApplicationFailedEvent is sent if there is an exception on startup.

...

vote vote

62

Why not just create a bean that starts your monitor on initialization, something like:

@Component public class Monitor {     @Autowired private SomeService service      @PostConstruct     public void init(){         // start your monitoring in here     } } 

the init method will not be called until any autowiring is done for the bean.

vote vote

53

The "Spring Boot" way is to use a CommandLineRunner. Just add beans of that type and you are good to go. In Spring 4.1 (Boot 1.2) there is also a SmartInitializingBean which gets a callback after everything has initialized. And there is SmartLifecycle (from Spring 3).

Top 3 video Explaining java - Running code after Spring Boot starts

Related QUESTION?