You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Bean生命周期:IOC容器内部实现及Bean创建后至销毁前过程咨询

Spring Bean 生命周期与IOC容器实现机制详解

Hey there! Let's break down these core Spring concepts with clear, practical explanations—no jargon overload, promise.


IOC容器的内部实现机制

Think of the IOC (Inversion of Control) container as a smart, self-managing factory for all your application's beans. Its internal workflow revolves around four key stages:

  • BeanDefinition 解析与注册
    First, Spring scans your configuration (whether it's @Configuration classes, XML files, or component scans) and translates each bean's metadata (class name, scope, dependencies, init/destroy methods) into a BeanDefinition object. This is like storing a detailed recipe for each product in the factory's database. These definitions are then registered with a BeanDefinitionRegistry, the central repository for all bean blueprints.

  • BeanFactory 体系
    The heart of the container is the BeanFactory interface—this is the basic "factory" that handles bean creation and lookup. DefaultListableBeanFactory is the most common concrete implementation. For more features (like AOP, internationalization, event publishing), we use ApplicationContext, which builds on BeanFactory and adds extra utilities, making it the go-to for most applications.

  • Bean实例化与依赖注入
    When a bean is first requested (or on container startup for singletons), the container pulls the corresponding BeanDefinition, uses reflection to create a raw bean instance, then resolves and injects its dependencies. This can happen via constructor injection, setter methods, or @Autowired annotations. Spring also handles circular dependencies using a three-level cache mechanism to avoid infinite loops.

  • Lifecycle management
    Once instantiated and injected, the container takes over managing the bean's lifecycle—from initialization to destruction—using hooks and callbacks we'll cover next.


Spring Bean 完整生命周期

Let's walk through the full journey of a bean from container startup to shutdown:

  1. BeanDefinition Registration: As mentioned above, the container first registers all bean blueprints.
  2. Bean Instantiation: The container creates a raw object instance using reflection (singletons are created on startup by default; prototypes are created per request).
  3. Dependency Injection: The container injects all required dependencies (other beans or values) into the bean's properties.
  4. Aware Interface Callbacks: If the bean implements interfaces like BeanNameAware, BeanFactoryAware, or ApplicationContextAware, the container calls their respective methods (e.g., setBeanName()) to pass in context info like the bean's ID or the container itself.
  5. BeanPostProcessor Pre-Initialization: All registered BeanPostProcessor beans run their postProcessBeforeInitialization() method. This is a powerful extension point—you can modify the bean instance or its properties before initialization.
  6. Initialization Methods:
    • If the bean implements InitializingBean, the afterPropertiesSet() method is called.
    • Any method marked with @PostConstruct runs next.
    • Finally, a custom init-method (configured via XML or @Bean(initMethod = "...")) executes.
  7. BeanPostProcessor Post-Initialization: All BeanPostProcessors run postProcessAfterInitialization(). This is where Spring creates dynamic proxies for AOP, for example.
  8. Bean is Ready for Use: The bean is now fully initialized and available for the application to use. Singletons are cached in the container; prototypes are handed off to the caller.
  9. Bean Destruction: When the container shuts down, destruction hooks are triggered (more on this below).

Bean创建完成后到销毁前的过程

Once a bean is ready for use, it lives through two main phases until destruction:

  • Active Usage: The bean is used to handle business logic—this is its "working life." For singletons, the container holds onto the instance and reuses it for all requests. For prototypes, the container doesn't track the instance after creation, so the caller is responsible for managing it (though Spring will still run destruction methods if configured, if you manually trigger them).

  • Pre-Destruction Callback Phase: When the container is shutting down (e.g., a web app stops, or you call context.close()), the container triggers these steps for eligible beans:

    1. Any method marked with @PreDestroy is executed first.
    2. If the bean implements DisposableBean, the destroy() method is called.
    3. Finally, a custom destroy-method (configured via XML or @Bean(destroyMethod = "...")) runs.

Note: Prototype beans don't get automatic destruction callbacks from Spring—you'll need to manually call their destroy methods if needed.


内容的提问来源于stack exchange,提问作者Ajay Chaurasia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:23:34