Spring Bean Lifecycle
How Spring Manage Bean
ApplicationContext
is an interface in Spring that provides configuration information to an application. It's the central interface in a Spring application. ApplicationContext is responsible for instantiating, configuring, and assembling beans. It reads configuration metadata to determine what objects to instantiate, configure, and assemble.
ApplicationContext provides basic features, including:
-
Publishing events to registered listeners
-
Methods for accessing application components
-
Internationalization support
-
Loading file resources
ApplicationContext is read-only while the application is running, but it can be reloaded if the implementation supports it. ApplicationContext is different from BeanFactory. BeanFactory creates a bean object when the getBean()
method is called. ApplicationContext loads all the beans and creates objects at startup.
Lifecycle
From the perspective of ApllicationContext
,
-
Spring reads the bean configuration and metadata, by creating
BeanDefinitionObject
for each beanThe bean configuration can be from
XML
orAnnotation
-
Spring executes all the custom
BeanFactoryPostProcessor
hooks to modify a bean definitionIn
AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization
, it will executes all theBeanFactoryPostProcessor
hook one by one. -
After the bean definitions are set up, Spring will executes the following steps for each bean
- Create a bean using its bean definition
- Set the propeties and the dependencies of the Bean
- Executes the
BeanPostProcessor
hook to allow modify the bean -
Executes the
PostConstruct
method defined in the bean, it's done byBeanPostProcessor
In
InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization
andInitDestroyAnnotationBeanPostProcessor.invokeInitMethods
, it executes the post init methods.PostConstruct
is a J2EE standard annotation. 5. Executes theafterPropertiesSet
method in a bean, it's done byBeanPostProcessor
afterPropertiesSet
is Spring way to post init a bean -
Executes custom bean initialization method, it's done by
BeanPostProcessor
Bean initialization methods can be specified either in the value of the init- method attribute in the corresponding
element in a Spring XML configuration or in the initMethod property of the @Bean annotation. The method will be only invoked once.
-
When the Spring application context is to shut down, the beans will be destoried in the following order
-
Executes the
PreDestroy
method -
Executes destroy method that implementing the DisposableBean interface
The method will be only invoked once.
-
Executes custom bean destory method
Bean destruction methods can be specified either in the value of the destroy-method attribute in the corresponding
element in a Spring XML configuration or in the destroyMethod property of the @Bean annotation. Destory method will be only execueted once
-