文章目录
什么是spring bean,这个问题,不用赘述。在学习spring bean的时候,其实只要明确spring bean是由Spring容器来管理的一个java对象即可。我们真正应该聚焦的我们能够在Spring容器管理spring bean的时候,做点什么?
什么是spring bean?
- spring bean本质也是java 对象,只不过区别在于它的创建和销毁是由spring容器来管理的
spring bean的Life Cycle
- spring bean在spring容器中,总共只有以下四个阶段
- instantiation 实例化
- populate values 注入初始值
- initialization 初始化
- destroy 销毁
在Spring bean的生命周期里,我们可以做什么?
- Spring framework提供了五种方式来影响spring bean的创建和销毁
- InitializingBean 和 DisposableBean 回调接口
- 针对特定的事件提供了 *Aware interfaces
- 用户自己手动指定 init() and destroy()方法
- @PostConstruct and @PreDestroy annotations
- BeanPostProcesser接口,需要明确的是BeanPostProcesser是针对所有spring bean的。而上述4种,都只针对于实现了对应接口的bean。
上述操作spring-bean是在哪个阶段执行的呢?
InitializingBean、DisposableBean和手动指定的区别
- InitializingBean、DisposableBean和手动指定 init() and destroy()本质是一样的。官方上建议手动指定,因为可以和Spring class解耦。个人理解这部分其实在使用的时候并没有什么差别。
现有Aware接口
接口 | 提供的方法 | 目的 |
---|---|---|
ApplicationContextAware | void setApplicationContext (ApplicationContext applicationContext) throws BeansException; | Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in. |
ApplicationEventPublisherAware | void setApplicationEventPublisher (ApplicationEventPublisher applicationEventPublisher); | Set the ApplicationEventPublisher that this object runs in. |
BeanClassLoaderAware | void setBeanClassLoader (ClassLoader classLoader); | Callback that supplies the bean class loader to a bean instance. |
BeanFactoryAware | void setBeanFactory (BeanFactory beanFactory) throws BeansException; | Callback that supplies the owning factory to a bean instance. |
BeanNameAware | void setBeanName(String name); | Set the name of the bean in the bean factory that created this bean. |
BootstrapContextAware | void setBootstrapContext (BootstrapContext bootstrapContext); | Set the BootstrapContext that this object runs in. |
LoadTimeWeaverAware | void setLoadTimeWeaver (LoadTimeWeaver loadTimeWeaver); | Set the LoadTimeWeaver of this object’s containing ApplicationContext. |
MessageSourceAware | void setMessageSource (MessageSource messageSource); | Set the MessageSource that this object runs in. |
NotificationPublisherAware | void setNotificationPublisher (NotificationPublisher notificationPublisher); | Set the NotificationPublisher instance for the current managed resource instance. |
PortletConfigAware | void setPortletConfig (PortletConfig portletConfig); | Set the PortletConfig this object runs in. |
ServletConfigAware | void setServletConfig (ServletConfig servletConfig); | Set the ServletConfig that this object runs in. |
ServletContextAware | void setServletContext (ServletContext servletContext); | Set the ServletContext that this object runs in. |
相关代码
参考文章
- https://howtodoinjava.com/spring-core/spring-bean-life-cycle/
- https://www.tutorialspoint.com/spring/spring_bean_post_processors.htm