DEV Community

eidher
eidher

Posted on • Updated on

The Spring Bean Lifecycle

Initialization

ApplicationContext context = SpringApplication.run(AppConfig.class);
Enter fullscreen mode Exit fullscreen mode
  1. Load and process bean definitions: @Configuration classes are processed, @Components are scanned, XML files are parsed, bean definitions are added to a BeanFactory, BeanFactoryPostProcessor beans are invoked.
    1. Load bean definitions
    2. Post process bean definitions
  2. Perform bean creation (for each bean): each bean is eagerly instantiated by default (unless marked as lazy), each bean goes through a post-processing phase.
    1. Find and create its dependencies
    2. Instantiate beans (dependency injection)
    3. Call setters (dependency injection)
    4. Bean Post Processors
      1. BeforeInit: modify a bean before initialization
      2. Initializer: initialization methods are called (@PostConstruct, @resource, etc)
      3. AfterInit: modify a bean after initialization
    5. Bean ready for use

Usage

AppService service = context.getBean("appService", AppService.class);
service.doSomething();
Enter fullscreen mode Exit fullscreen mode

When you invoke a bean obtained from the context. If the bean is wrapped by a proxy the proxy is created during the initialization phase by a BeanPostProcessor adding behavior to the bean. It may be a JDK Proxy (interface based) or a CGLib Proxy (subclass based)

Destruction

context.close();
Enter fullscreen mode Exit fullscreen mode

The context is closed if the application shuts down (not killed or failed), all beans are cleaned up, @PreDestroy methods are invoked, beans are released for the Garbage Collector to destroy.

Top comments (0)