Thumbnail image

Spring Boot: Startup init through @PostConstruct

Tue, Mar 9, 2021 One-minute read

There are frequent situations when application requires running 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
  }
}