Image for post
Image for post

Spring Boot: Startup init through @PostConstruct

David Marko
Jan 23, 2017 · 1 min read

There are frequent situations when application requires to run custom code while starting up. There are several ways how to do it in Spring Boot, one of my favorites is to create @Component class with method annotated with @PostConstruct . This simple component class is scanned during Spring Boot application start and method annotated by @PostConstruct is run just after all services initialized. Such startup init component can inject / autowire custom managed services and use them for initialization. This way we can, for example, inject Spring Data repository and do some data initialization in our application.

The following code example is minimum class skeleton for our startup init class. We can have several @Component classes in our application with @PostConstruct annotation available. All these are going to be run during Spring Boot start up process.

@Component
public class StartUpInit {
@Autowired
CustomServiceExample customServiceExample;
@PostConstruct
public void init(){
// init code goes here
}
}

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store