🌱 Spring Bean
🧠 What is a Bean in Spring Boot?
A bean is a Java object managed by the Spring framework. In Spring Boot, you often create beans using:
@Component
@Service
@Repository
@Configuration
@Bean
Spring Boot automatically detects and manages these beans through component scanning.
🔄 How Does the Bean Lifecycle Work in Spring Boot?
Spring Boot uses the standard Spring bean lifecycle, but simplifies it with annotations and auto-configuration.
✅ Common Lifecycle Hooks You Might Use:
@PostConstruct - Run code after dependencies are injected:
@Component
public class MyService {
@PostConstruct
public void init() {
System.out.println("Bean is initialized");
}
}
@PreDestroy - Run code before bean is destroyed (e.g., app shutdown):
@PreDestroy
public void cleanup() {
System.out.println("Bean is being destroyed");
}
InitializingBean and DisposableBean interfaces:
@Component
public class MyService implements InitializingBean, DisposableBean {
public void afterPropertiesSet() {
System.out.println("Bean initialized via InitializingBean");
}
public void destroy() {
System.out.println("Bean destroyed via DisposableBean");
}
}
@Bean(initMethod = ..., destroyMethod = ...) in @Configuration classes:
@Bean(initMethod = "start", destroyMethod = "stop")
public MyBean myBean() {
return new MyBean();
}
📦 Summary (Spring Boot Way)
| Stage | What You Use |
|---|---|
| Initialization | @PostConstruct, InitializingBean, initMethod |
| Destruction | @PreDestroy, DisposableBean, destroyMethod |
✅ Spring Bean Life Cycle (Super Simple)
- Create – Spring creates the object (bean).
- Inject – Spring injects dependencies (like other beans).
- Initialize – Spring runs setup code (
@PostConstruct). - Use – The bean is ready to be used.
- Destroy – Spring runs cleanup code (
@PreDestroy).
🔁 One Line Summary:
Spring creates, injects, initializes, uses, and destroys your beans automatically.
Comments
Post a Comment