Understanding Spring Bean Lifecycle in Java Development

Understanding the 𝗦𝗽𝗿𝗶𝗻𝗴 𝗕𝗲𝗮𝗻 𝗟𝗶𝗳𝗲𝗰𝘆𝗰𝗹𝗲 is the "level up" every Java developer needs. It’s not just about creating objects; it’s about how Spring manages their entire existence—from birth to destruction. 📍 𝗣𝗵𝗮𝘀𝗲 𝟭: 𝗧𝗵𝗲 𝗦𝗰𝗼𝗽𝗲𝘀 (𝗪𝗵𝗲𝗿𝗲 & 𝗛𝗼𝘄 𝗹𝗼𝗻𝗴?) Before a bean is born, Spring needs to know its scope. Here are the most common ones:  • 𝗦𝗶𝗻𝗴𝗹𝗲𝘁𝗼𝗻 (𝗗𝗲𝗳𝗮𝘂𝗹𝘁): One instance per Spring IoC container. Perfect for stateless services.  • 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲: A new instance every time it's requested. Use this for stateful beans.  • 𝗥𝗲𝗾𝘂𝗲𝘀𝘁: One instance per HTTP request (Web-aware).  • 𝗦𝗲𝘀𝘀𝗶𝗼𝗻: One instance per HTTP session.  • 𝗔𝗽𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻/𝗚𝗹𝗼𝗯𝗮𝗹 𝗦𝗲𝘀𝘀𝗶𝗼𝗻: Scoped to the Lifecycle of a ServletContext. ⚙️ 𝗣𝗵𝗮𝘀𝗲 𝟮: 𝗧𝗵𝗲 𝗟𝗶𝗳𝗲𝗰𝘆𝗰𝗹𝗲 (𝗧𝗵𝗲 "𝗛𝗼𝘄") The journey of a Bean follows a very specific path:  • 𝗜𝗻𝘀𝘁𝗮𝗻𝘁𝗶𝗮𝘁𝗶𝗼𝗻: The JVM creates the bean instance.  • 𝗣𝗼𝗽𝘂𝗹𝗮𝘁𝗲 𝗣𝗿𝗼𝗽𝗲𝗿𝘁𝗶𝗲𝘀: Dependency Injection (DI) happens here.  • 𝗔𝘄𝗮𝗿𝗲 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲𝘀: Spring calls setBeanName, setBeanFactory, etc.  • 𝗕𝗲𝗮𝗻 𝗣𝗼𝘀𝘁-𝗣𝗿𝗼𝗰𝗲𝘀𝘀𝗼𝗿𝘀 (𝗕𝗲𝗳𝗼𝗿𝗲 𝗜𝗻𝗶𝘁): Custom logic before the bean is ready.  • 𝗜𝗻𝗶𝘁𝗶𝗮𝗹𝗶𝘇𝗮𝘁𝗶𝗼𝗻: @PostConstruct or afterPropertiesSet() is triggered.  • 𝗕𝗲𝗮𝗻 𝗣𝗼𝘀𝘁-𝗣𝗿𝗼𝗰𝗲𝘀𝘀𝗼𝗿𝘀 (𝗔𝗳𝘁𝗲𝗿 𝗜𝗻𝗶𝘁): The bean is wrapped (e.g., for AOP/Proxies).  • 𝗥𝗘𝗔𝗗𝗬: The bean is now live in the container!  • 𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝗶𝗼𝗻: When the context closes, @PreDestroy cleans everything up. #SpringBoot #Java #BackendDevelopment #SoftwareEngineering #SpringFramework #CodingTips

Thanks for sharing 😊

Like
Reply

To view or add a comment, sign in

Explore content categories