DEV Community

eidher
eidher

Posted on • Edited on

4 2

@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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay