Sobes.tech
Senior

What are @PreDestroy and @PostConstruct?

sobes.tech AI

Answer from AI

@PostConstruct and @PreDestroy are annotations from the Java EE specification (for example, in Jakarta EE or Spring) used to manage the lifecycle of beans (objects).

  • @PostConstruct marks a method that should be called immediately after the bean has been created and all dependencies have been injected. This is convenient for initialization, configuration, or starting some processes.

  • @PreDestroy marks a method that is called before the bean is destroyed, for example, to release resources, close connections, etc.

Example of usage in Spring:

@Component
public class MyBean {

    @PostConstruct
    public void init() {
        System.out.println("Bean initialized");
    }

    @PreDestroy
    public void cleanup() {
        System.out.println("Bean is being destroyed");
    }
}

Thus, these annotations help manage the lifecycle of components without the need to explicitly call initialization and cleanup methods.