In this tutorial, we will see how to run code immediately after spring boot application start. There are cases where we need to run tasks after application started.
- upgrade step to update DB data
- update config
- clear cache in redis
- Make API call to load external config into DB
- load config from DB to System.properties
In the above cases , we need to configured some logic which should be executed after spring boot applications start. The below are multiple ways to achieve this.
1. EventListener annotation:
The below is code for EventListener and this is recommended approach:
import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; @Component public class StartupLogicRunner {
@Autowired private UpgradeService upgradeService;@EventListener public void handleContextRefresh(ContextRefreshedEvent event) { // Your logic here System.out.println("Application started successfully!");
upgradeService.handleDBUpdate_v.10();
} }
2. Using ApplicationListener
The below is example code with ApplicationListener:
import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; @Component public class SpringBootUpgradeStep implements ApplicationListener<ContextRefreshedEvent> {
@Autowired private UpgradeService upgradeService;@Override public void onApplicationEvent(ContextRefreshedEvent event) { // Your logic here System.out.println("Application started successfully!"); upgradeService.handleDBUpdate_v.10(); } }
3. Using PostConstruct Annotation:
The below is sample code using PostConstruct :
import javax.annotation.PostConstruct; import org.springframework.stereotype.Component; @Component public class StartupLogicRunner {
@Autowired private UpgradeService upgradeService;@PostConstruct public void init() { // Your logic here System.out.println("Application started successfully!");
upgradeService.handleDBUpdate_v.10();} }
4. Using InitializingBean interface:
The below is sample code for Initializing Bean:
import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; @Component public class StartupLogicRunner implements InitializingBean {
@Autowired private UpgradeService upgradeService;@Override public void afterPropertiesSet() throws Exception { // Your logic here System.out.println("Application started successfully!");
upgradeService.handleDBUpdate_v.10();} }
5. Using CommandLineRunner
The below is sample for CommandLineRunner
@Component
public class StartupRunner implements CommandLineRunner {
@Override
public void run(String...args) throws Exception {
System.out.println("Application started successfully!");
}
}
Thanks for Reading…