What if your app could prepare and clean up itself perfectly every time, without you lifting a finger?
Why @PostConstruct and @PreDestroy in Spring Boot? - Purpose & Use Cases
Imagine you have a Java class that needs to open a database connection when it starts and close it when it stops. You write code to do this manually in many places, like constructors and shutdown hooks.
Manually managing setup and cleanup is tricky. You might forget to close resources, causing memory leaks. It's hard to keep track of when to run this code, especially as your app grows.
@PostConstruct and @PreDestroy let you mark methods to run automatically right after creation and just before destruction of a Spring bean. This keeps setup and cleanup neat and reliable.
public class MyService {
public MyService() {
openConnection();
}
public void close() {
closeConnection();
}
}import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; public class MyService { @PostConstruct public void init() { openConnection(); } @PreDestroy public void cleanup() { closeConnection(); } }
This makes your app safer and easier to maintain by automating resource setup and cleanup at the right times.
Think of a coffee machine that automatically heats water when turned on and cleans itself before turning off. @PostConstruct and @PreDestroy do the same for your app's resources.
Manual resource management is error-prone and hard to track.
@PostConstruct runs setup code after bean creation.
@PreDestroy runs cleanup code before bean destruction.
Practice
@PostConstruct annotation in a Spring Boot application?Solution
Step 1: Understand the role of @PostConstruct
@PostConstruct is used to run initialization code after the Spring bean is fully created and dependencies are set.Step 2: Compare with other lifecycle annotations
@PreDestroy runs before bean removal, and scheduling annotations run repeatedly, so they don't match @PostConstruct's purpose.Final Answer:
To run a method immediately after the bean is created and dependencies are injected -> Option AQuick Check:
@PostConstruct = run after bean creation [OK]
- Confusing @PostConstruct with @PreDestroy
- Thinking @PostConstruct runs before bean creation
- Assuming it schedules repeated tasks
@PreDestroy in a Spring Boot bean?Solution
Step 1: Identify correct usage of @PreDestroy
@PreDestroy is placed on a method to run cleanup code before the bean is destroyed.Step 2: Eliminate incorrect options
@PreDestroy cannot annotate a class or constructor, and static methods are not lifecycle callbacks.Final Answer:
Annotate a method with @PreDestroy to run cleanup code before bean destruction -> Option BQuick Check:
@PreDestroy = method cleanup before bean removal [OK]
- Annotating the class instead of a method
- Using @PreDestroy on constructors
- Marking static methods with @PreDestroy
public class MyBean {
@PostConstruct
public void init() {
System.out.println("Bean is initialized");
}
@PreDestroy
public void cleanup() {
System.out.println("Bean is about to be destroyed");
}
}What will be printed when the application context starts and then shuts down?
Solution
Step 1: Understand @PostConstruct behavior on startup
The init() method runs after bean creation, printing "Bean is initialized" when the app context starts.Step 2: Understand @PreDestroy behavior on shutdown
The cleanup() method runs before bean destruction, printing "Bean is about to be destroyed" when the app context shuts down.Final Answer:
Bean is initialized
Bean is about to be destroyed -> Option CQuick Check:
Startup prints init, shutdown prints cleanup [OK]
- Mixing order of printed messages
- Expecting only one message to print
- Thinking @PreDestroy runs on startup
public class ResourceBean {
@PostConstruct
public void setup() {
System.out.println("Setup resources");
}
@PreDestroy
public void cleanup() {
System.out.println("Cleanup resources");
}
public void start() {
System.out.println("Start method called");
}
}When running the application, the developer notices that "Cleanup resources" is never printed on shutdown. What is the most likely cause?
Solution
Step 1: Check if bean is managed by Spring
@PostConstruct and @PreDestroy only work if Spring manages the bean lifecycle (e.g., via @Component or @Bean).Step 2: Understand why cleanup isn't called
If the bean is created manually (new keyword), Spring won't call lifecycle methods, so cleanup() won't run automatically.Final Answer:
The bean is not managed by Spring, so lifecycle annotations are ignored -> Option DQuick Check:
Lifecycle annotations need Spring-managed beans [OK]
- Thinking @PreDestroy must be static
- Assuming @PostConstruct blocks @PreDestroy
- Believing cleanup() runs without Spring management
@PostConstruct and @PreDestroy to achieve this?Solution
Step 1: Identify correct lifecycle method usage
@PostConstruct should open the connection after bean creation; @PreDestroy should close it before destruction.Step 2: Check code correctness
public class DbBean { private Connection conn; @PostConstruct public void open() { conn = DriverManager.getConnection("url"); System.out.println("Connection opened"); } @PreDestroy public void close() { conn.close(); System.out.println("Connection closed"); } } correctly uses @PostConstruct to open and @PreDestroy to close the connection with proper method calls.Final Answer:
public class DbBean { private Connection conn; @PostConstruct public void open() { conn = DriverManager.getConnection("url"); System.out.println("Connection opened"); } @PreDestroy public void close() { conn.close(); System.out.println("Connection closed"); } } -> Option AQuick Check:
Open after creation, close before destruction [OK]
- Swapping @PostConstruct and @PreDestroy methods
- Not calling connection methods inside lifecycle methods
- Missing lifecycle annotations on resource methods
Ready to prove it?
Pass the test and this pattern moves unknown
