Junior — Middle
Can you explain the stages of the Bean object lifecycle within the framework you use?
sobes.tech AI
Answer from AI
The lifecycle of a Bean in Java frameworks (e.g., Spring) typically includes several key stages:
- Creation (Instantiation) — the container creates an instance of the Bean, usually via a constructor.
- Dependency Injection — the container injects necessary dependencies into fields or through setters.
- Initialization — initialization methods are called, such as methods annotated with
@PostConstructor implementing theInitializingBeaninterface. - Usage — the Bean is ready for use and is used in the application.
- Destruction — when the container shuts down, destruction methods are called, such as those annotated with
@PreDestroyor implementing theDisposableBeaninterface.
Example using annotations in Spring:
@Component
public class MyBean {
@PostConstruct
public void init() {
// initialization code
}
@PreDestroy
public void cleanup() {
// cleanup code
}
}