Junior — Middle
What annotations are used to define the lifecycle stages of beans in a container?
sobes.tech AI
Answer from AI
In Java, annotations are used to manage the lifecycle of beans in a container (for example, in Spring):
@PostConstruct— a method with this annotation is called after the bean is created and dependencies are injected, used for initialization.@PreDestroy— the method is called before the bean is destroyed, for resource cleanup.
Example:
@Component
public class MyBean {
@PostConstruct
public void init() {
// initialization
}
@PreDestroy
public void cleanup() {
// resource cleanup
}
}
Also, in Spring, you can implement the InitializingBean and DisposableBean interfaces for the same purposes, but annotations are more convenient and readable.