0
0
Spring Bootframework~30 mins

@PostConstruct and @PreDestroy in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @PostConstruct and @PreDestroy in Spring Boot
📖 Scenario: You are building a simple Spring Boot service that needs to perform setup right after the service starts and cleanup just before it stops.This is like preparing your kitchen before cooking and cleaning it after you finish.
🎯 Goal: Create a Spring Boot component that uses @PostConstruct to run initialization code after the bean is created, and @PreDestroy to run cleanup code before the bean is destroyed.
📋 What You'll Learn
Create a Spring component class named KitchenService
Add a method annotated with @PostConstruct that prints "Kitchen is ready"
Add a method annotated with @PreDestroy that prints "Kitchen is cleaned"
Use the System.out.println statements exactly as specified
💡 Why This Matters
🌍 Real World
Many applications need to initialize resources like database connections or caches after startup and release them before shutdown to avoid resource leaks.
💼 Career
Understanding bean lifecycle annotations like @PostConstruct and @PreDestroy is essential for writing robust Spring Boot applications that manage resources properly.
Progress0 / 4 steps
1
Create the KitchenService class
Create a public class named KitchenService annotated with @Component.
Spring Boot
Need a hint?

Use @Component to make the class a Spring bean.

2
Add @PostConstruct method
Inside KitchenService, add a public method named init annotated with @PostConstruct that calls System.out.println("Kitchen is ready").
Spring Boot
Need a hint?

Use @PostConstruct to mark the method that runs after bean creation.

3
Add @PreDestroy method
Inside KitchenService, add a public method named cleanup annotated with @PreDestroy that calls System.out.println("Kitchen is cleaned").
Spring Boot
Need a hint?

Use @PreDestroy to mark the method that runs before bean destruction.

4
Complete the Spring Boot application
Create a SpringBootApplication class named KitchenApp with a main method that runs the application using SpringApplication.run(KitchenApp.class, args).
Spring Boot
Need a hint?

This class starts the Spring Boot application.