Junior — Middle
Can you explain the stages and management of the lifecycle of a Spring Bean object?
sobes.tech AI
Answer from AI
The Spring Bean lifecycle is the sequence of stages that an object (Bean) goes through in the Spring container, from creation to destruction. Lifecycle management allows for additional initialization and cleanup.
Main lifecycle stages:
- Creation of the instance — Spring creates the Bean object, usually via the constructor.
- Dependency injection — the container sets all necessary dependencies (via setters or constructor).
- Calling initialization methods — if the Bean implements the
InitializingBeaninterface, theafterPropertiesSet()method is called. You can also specify an initialization method via the@PostConstructannotation or in the configuration. - Bean is ready for use — the object is available for use in the application.
- Destruction of the Bean — when the container shuts down, cleanup methods are called, such as
destroy()from theDisposableBeaninterface or a method annotated with@PreDestroy.
Example with annotations:
@Component
public class MyBean {
@PostConstruct
public void init() {
// initialization code
}
@PreDestroy
public void cleanup() {
// cleanup code
}
}
Thus, Spring provides flexible mechanisms for managing the Bean lifecycle, helping control creation, configuration, and destruction of objects.