DEV Community 👩‍💻👨‍💻

eidher
eidher

Posted 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

Top comments (0)

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠