Junior — Middle
How does Spring manage and interact with objects and their lifecycle?
sobes.tech AI
Answer from AI
In Spring, object management and their lifecycle are handled through the Inversion of Control (IoC) container. The container creates, configures, and manages the lifecycle of beans (objects) declared in the configuration (annotations, XML, or Java configuration).
Main points:
- The container creates objects (beans) at application startup or on demand.
- Dependency injection occurs automatically via constructors, setters, or fields.
- The bean's lifecycle can be controlled using methods and annotations, such as
@PostConstructand@PreDestroy.
Example:
@Component
public class MyService {
@Autowired
private MyRepository repository;
@PostConstruct
public void init() {
// initialization after bean creation
}
@PreDestroy
public void cleanup() {
// cleanup before bean destruction
}
}