0
0
Spring Bootframework~30 mins

Bean lifecycle overview in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Bean lifecycle overview
📖 Scenario: You are building a simple Spring Boot application that manages a bean representing a user service. You want to understand how Spring creates, initializes, and destroys beans during the application lifecycle.
🎯 Goal: Create a Spring Boot bean called UserService and demonstrate the bean lifecycle by adding initialization and destruction methods.
📋 What You'll Learn
Create a bean class named UserService
Add a method annotated with @PostConstruct for initialization
Add a method annotated with @PreDestroy for cleanup
Configure the bean in the Spring context using @Component
Create a main Spring Boot application class to run the context
💡 Why This Matters
🌍 Real World
Understanding bean lifecycle helps you manage resources like database connections or caches properly in real Spring applications.
💼 Career
Spring Boot is widely used in enterprise Java development; knowing bean lifecycle is essential for building robust and maintainable applications.
Progress0 / 4 steps
1
Create the UserService bean class
Create a class named UserService in package com.example.demo and annotate it with @Component.
Spring Boot
Need a hint?

Use @Component to tell Spring this is a bean.

2
Add initialization method with @PostConstruct
Inside UserService, add a method named init annotated with @PostConstruct that prints "UserService initialized".
Spring Boot
Need a hint?

Use @PostConstruct to run code after bean creation.

3
Add destruction method with @PreDestroy
Inside UserService, add a method named cleanup annotated with @PreDestroy that prints "UserService destroyed".
Spring Boot
Need a hint?

Use @PreDestroy to run code before bean destruction.

4
Create main Spring Boot application class
Create a class named DemoApplication in package com.example.demo with @SpringBootApplication annotation and a main method that runs SpringApplication.run(DemoApplication.class, args).
Spring Boot
Need a hint?

This class starts the Spring Boot application.