DEV Community

eidher
eidher

Posted on • Updated on

@PostConstruct and @PreDestroy in Spring

@PostConstruct adds behavior at startup (after all dependency injection, constructors, and setters) and @PreDestroy adds behavior at shutdown (prior to destroying the bean instance, when a configurable application context is closed and if application shuts down normally. Not called for prototype beans). The annotated methods can have any visibility but must take no parameters and only return void.

@PostConstruct
void populateCache() {
  ...
}

@PreDestroy 
void flushCache() {
  ...
}
Enter fullscreen mode Exit fullscreen mode

Alternatively, the @Bean annotation has the initMethod and destroyMethod options:

@Bean(initMethod="populateCache", destroyMethod="flushCache")
public Repository repository() {
  ...
}

Enter fullscreen mode Exit fullscreen mode

Latest comments (0)