DEV Community


Posted on

The Spring Bean Lifecycle


ApplicationContext context =;
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


AppService service = context.getBean("appService", AppService.class);
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)


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.

Discussion (0)