The Spring Bean Lifecycle: @PostConstruct and @PreDestroy
EmailNotifier connects to the mail server once when Spring builds it and disconnects once when the context closes. @PostConstruct and @PreDestroy do it, main never calls either, and without context.close() the disconnect never runs.
What you will learn
- Run setup code once after Spring builds a bean with @PostConstruct
- Run clean-up code once when the context closes with @PreDestroy
- Add the jakarta.annotation-api dependency these annotations need
- Explain why forgetting context.close() skips @PreDestroy
Before you start
- Spring Stereotype Annotations
- Spring Bean Scopes
Our EmailNotifier needs a mail server. When the app starts it should connect once; while it runs it sends many emails; when it closes it should disconnect once. The catch: Spring builds this bean, not us. So Spring has to tell the bean when to start and when to stop.
A shop: open once, close once
In the morning the shopkeeper rolls up the shutter, once. All day the shop serves customers, many times. At night the shopkeeper counts the till and closes, once. In Spring, opening is @PostConstruct, serving is a normal method, and closing is @PreDestroy.
Inside EmailNotifier
package org.studyeasy.blog;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;
// Sends emails. It connects to the mail server once at the start
// and disconnects once at the end - Spring calls both methods for us.
@Component
public class EmailNotifier {
@PostConstruct
public void connect() {
System.out.println("Connected to mail server");
}
public void send(String title) {
System.out.println("Email sent: " + title);
}
@PreDestroy
public void disconnect() {
System.out.println("Disconnected from mail server");
}
}
Spring calls connect once, right after it builds the bean. send is ordinary; PostService calls it. Spring calls disconnect once, when the context closes.
These two annotations don't come from Spring. They live in jakarta.annotation, so the pom needs one extra dependency next to spring-context:
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>3.0.0</version>
</dependency>
The rest is familiar
package org.studyeasy.blog;
import org.springframework.stereotype.Service;
// Publishes a post, then asks the notifier to tell the readers.
@Service
public class PostService {
private final EmailNotifier notifier;
public PostService(EmailNotifier notifier) {
this.notifier = notifier;
}
public void publish(String title) {
System.out.println("Post published: " + title);
notifier.send(title);
}
}
PostService just uses the notifier and knows nothing about connecting. BlogConfig is the usual @Configuration + @ComponentScan.
package org.studyeasy.blog;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class BlogApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(BlogConfig.class);
PostService service = context.getBean(PostService.class);
service.publish("Hello, Spring");
context.close();
}
}
Connected to mail server
Post published: Hello, Spring
Email sent: Hello, Spring
Disconnected from mail server
main never calls connect or disconnect. Starting the context builds EmailNotifier and calls connect; then it builds PostService with the notifier handed in. publish gives the middle two lines, and context.close() is what triggers disconnect.
Forget close()
Delete the last line of main, context.close();, and run again:
Connected to mail server
Post published: Hello, Spring
Email sent: Hello, Spring
There's no "Disconnected from mail server". Spring was never closed, so @PreDestroy never ran. Close the context at the end, or the clean-up code is simply skipped.
Common mistakes
- Leaving out the
jakarta.annotation-apidependency. The imports won't compile. - Also calling
connect()yourself frommain. Then it runs twice. - Putting the connection setup in a method nobody annotates. Spring only calls the methods it's told about.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
Spring in one line: a container that creates your classes and hands each one what it needs. Plus the Spring Framework 7 baseline (JDK 17 to 25, Jakarta EE 11, Tomcat 11, JUnit 6), what got better than Spring 6, and a two-line version check.
A Plain Spring Project, No Boot: Your First Bean With spring-context
One dependency, one recipe, one getBean: a Maven project with spring-context 7.0.9, a Blog record, an AppConfig with @Bean, and a main that asks the container for the Blog. Then delete @Bean and meet NoSuchBeanDefinitionException.
Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
A PostService needs a PostRepository. Build it three ways: the service calls new itself (tight coupling), main hands it in through the constructor (DI by hand), and the Spring container does the wiring from a @Configuration recipe.
Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
Instead of one @Bean method per class, put @Component on EmailNotifier and PostService and @ComponentScan on an empty BlogConfig. Spring walks the package, finds the stickers and builds the beans; main doesn't change.
