Sobes.tech
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:

  1. Creation (Instantiation) — the container creates an instance of the Bean, usually via a constructor.
  2. Dependency Injection — the container injects necessary dependencies into fields or through setters.
  3. Initialization — initialization methods are called, such as methods annotated with @PostConstruct or implementing the InitializingBean interface.
  4. Usage — the Bean is ready for use and is used in the application.
  5. Destruction — when the container shuts down, destruction methods are called, such as those annotated with @PreDestroy or implementing the DisposableBean interface.

Example using annotations in Spring:

@Component
public class MyBean {

    @PostConstruct
    public void init() {
        // initialization code
    }

    @PreDestroy
    public void cleanup() {
        // cleanup code
    }
}