Spring Bean生命周期:IOC容器内部实现及Bean创建后至销毁前过程咨询
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@Configurationclasses, XML files, or component scans) and translates each bean's metadata (class name, scope, dependencies, init/destroy methods) into aBeanDefinitionobject. This is like storing a detailed recipe for each product in the factory's database. These definitions are then registered with aBeanDefinitionRegistry, the central repository for all bean blueprints.BeanFactory 体系
The heart of the container is theBeanFactoryinterface—this is the basic "factory" that handles bean creation and lookup.DefaultListableBeanFactoryis the most common concrete implementation. For more features (like AOP, internationalization, event publishing), we useApplicationContext, which builds onBeanFactoryand 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 correspondingBeanDefinition, uses reflection to create a raw bean instance, then resolves and injects its dependencies. This can happen via constructor injection, setter methods, or@Autowiredannotations. 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:
- BeanDefinition Registration: As mentioned above, the container first registers all bean blueprints.
- Bean Instantiation: The container creates a raw object instance using reflection (singletons are created on startup by default; prototypes are created per request).
- Dependency Injection: The container injects all required dependencies (other beans or values) into the bean's properties.
- Aware Interface Callbacks: If the bean implements interfaces like
BeanNameAware,BeanFactoryAware, orApplicationContextAware, the container calls their respective methods (e.g.,setBeanName()) to pass in context info like the bean's ID or the container itself. - BeanPostProcessor Pre-Initialization: All registered
BeanPostProcessorbeans run theirpostProcessBeforeInitialization()method. This is a powerful extension point—you can modify the bean instance or its properties before initialization. - Initialization Methods:
- If the bean implements
InitializingBean, theafterPropertiesSet()method is called. - Any method marked with
@PostConstructruns next. - Finally, a custom
init-method(configured via XML or@Bean(initMethod = "...")) executes.
- If the bean implements
- BeanPostProcessor Post-Initialization: All
BeanPostProcessors runpostProcessAfterInitialization(). This is where Spring creates dynamic proxies for AOP, for example. - 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.
- 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:- Any method marked with
@PreDestroyis executed first. - If the bean implements
DisposableBean, thedestroy()method is called. - Finally, a custom
destroy-method(configured via XML or@Bean(destroyMethod = "...")) runs.
- Any method marked with
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

