Created
December 28, 2021 18:40
-
-
Save raja-anbazhagan/a8c470e71aadf017e096d5be0fd44c74 to your computer and use it in GitHub Desktop.
All possible ways to run code on application startup in Spring boot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.springhow.examples.springboot.startupcode; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.beans.factory.SmartInitializingSingleton; | |
import org.springframework.boot.ApplicationArguments; | |
import org.springframework.boot.ApplicationRunner; | |
import org.springframework.boot.CommandLineRunner; | |
import org.springframework.boot.context.event.ApplicationStartedEvent; | |
import org.springframework.boot.context.event.ApplicationStartingEvent; | |
import org.springframework.context.ApplicationContext; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.context.event.EventListener; | |
@Configuration | |
public class ApplicationStartupConfiguration { | |
private static final Logger log = LoggerFactory.getLogger(ApplicationStartupConfiguration.class); | |
@Bean | |
CommandLineRunner commandLineRunner() { | |
return new CommandLineRunner() { | |
@Override | |
public void run(String... args) throws Exception { | |
log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); | |
log.info("These Lines will get printed on application startup"); | |
log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); | |
} | |
}; | |
} | |
@Bean | |
ApplicationRunner applicationRunner() { | |
return new ApplicationRunner() { | |
@Override | |
public void run(ApplicationArguments args) throws Exception { | |
log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); | |
log.info("These Lines will get printed on application startup too"); | |
log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); | |
} | |
}; | |
} | |
@EventListener | |
public void executeOnStartup(ApplicationStartedEvent event) { | |
log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); | |
log.info("Another way to run something on application startup with event {}", event); | |
log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); | |
} | |
@Bean | |
SmartInitializingSingleton smartInitializingSingleton(ApplicationContext context) { | |
return () -> { | |
log.info("This runs on startup too... {}", context); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment