Bean lifecycle and scopes · Topic 2 of 5
Lifecycle callbacks
Definition​
Spring creates a bean, injects its dependencies, then calls your @PostConstruct method. When the application stops it calls your @PreDestroy method. Use them to open and close resources instead of doing that work in the constructor.
Example code​
The order: constructor, init, use, destroy
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
@Component
class ConnectionPool {
ConnectionPool() { System.out.println("1. constructor"); }
@PostConstruct
void open() { System.out.println("2. @PostConstruct: open connections"); }
void use() { System.out.println("3. in use"); }
@PreDestroy
void close() { System.out.println("4. @PreDestroy: close connections"); }
}
@ComponentScan
class Demo {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Demo.class)) {
context.getBean(ConnectionPool.class).use();
} // closing the context destroys the beans
}
}
// Output:
// 1. constructor
// 2. @PostConstruct: open connections
// 3. in use
// 4. @PreDestroy: close connections
Finished this page? Track your progress (saved only in your browser).