Bean的初始化和生命周期
bean 的生命周期
bean 创建—>初始化—>销毁的过程
Spring 容器管理 bean 的生命周期
对象创建
单实例:容器启动时创建对象
多实例:获取对象时创建对象
初始化:
销毁:
- 单实例:容器关闭时销毁
- 多实例:容器不会管理该bean,不会调用销毁方法
自定义初始化和销毁方法
1.指定初始化和销毁方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Car { public Car() { System.out.println("容器创建完成!"); } public void init() { System.out.println("方法被创建了!"); } public void destory() { System.out.println("方法被销毁了!"); } }
|
1 2 3 4 5 6 7 8 9 10
| @Configuration public class MainConfig {
@Bean(initMethod = "init",destroyMethod = "destroy") public Car car() { return new Car(); } }
|
2.让Bean实现 InitializingBean接口 和 DisposableBean接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class Car implements InitializingBean, DisposableBean {
public Car() { }
@Override public void destroy() throws Exception { System.out.println("销毁方法~"); }
@Override public void afterPropertiesSet() throws Exception { System.out.println("初始化方法~"); } }
|
3.可以用 JSR250:
@PostConstruct
:在bean创建完成并属性复制完成,执行初始化方法
PreDestroy
:在容器销毁bean之前通知我们进行销毁工作
1 2 3 4 5 6 7 8 9
| @PostConstruct public void init() { System.out.println("@PostConstruct"); }
@PreDestroy public void destroy() { System.out.println("@PreDestroy"); }
|
4.BeanPostProcessor
1 2 3 4 5 6 7 8 9 10 11 12 13
| public interface BeanPostProcessor { @Nullable default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; }
@Nullable default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }
|
BeanPostProcessor 原理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
populateBean(beanName, mbd, instanceWrapper);
{ wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName); this.invokeInitMethods(beanName, wrappedBean, mbd); wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); }
|
Spring底层对 BeanPostProcessor 的使用:
bean赋值、注入其他组件、@Autowired
、生命周期注解功能、@Async
、···
属性赋值:@Value
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Person {
@value("wxs") private String name; @value("#{20-2}") private Integer age; private String hobby; }
|
1 2 3 4 5 6 7 8 9
| @Configuration @PropertySource(value={"classpath:/person.properties"}) public class MainConfig {
public Person person() { return new Person(); } }
|
1 2
| person.hobby = singJumpRapAndBasketball
|
环境切换:@Profile
@Profile
注解:逻辑组名称,只有当这些Profile被激活的时候,才会将Profile中所对应的Bean注册到Spring容器中。
- 加了环境标识的bean,只有环境被激活才会被注册到容器中
- 写在配置类上,只有是指定的环境的时候,整个配置类里面的所有配置才能开始生效
- 没有标注环境标识的bean,在任何环境下都加载
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Profile("dev") public DataSource dataSourceDev(){ ... }
@Profile("test") public DataSource dataSourceTest(){ ... }
@Profile("prod") public DataSource dataSourceProd(){ ... }
|
激活方法:
使用命令行动态参数: 设置虚拟机参数 -Dspring.profiles.active=test/dev/prod
-
1 2 3 4 5 6 7 8 9 10 11
| AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
context.getEnvironment().setDefaultProfiles("test");
context.register(MainConfig.class);
context.refresh();
|
Spring容器创建原理【源码分析】
Spring 通过AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfAOP.class)
来创建容器,
我们就进到 AnnotationConfigApplicationContext 中一探究竟!
==注:以下代码均只截取了源码中重要的部分,并不是完整的源码==
重点关注容器的刷新过程!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public void refresh() { this.prepareRefresh(); ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory(); this.prepareBeanFactory(beanFactory);
this.postProcessBeanFactory(beanFactory); this.invokeBeanFactoryPostProcessors(beanFactory); this.registerBeanPostProcessors(beanFactory); this.initMessageSource(); this.initApplicationEventMulticaster(); this.onRefresh(); this.registerListeners(); this.finishBeanFactoryInitialization(beanFactory); this.finishRefresh();
this.destroyBeans(); this.cancelRefresh(var9);
this.resetCommonCaches(); }
|
1. prepareRefresh():刷新前的预处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| protected void prepareRefresh() { this.startupDate = System.currentTimeMillis(); this.closed.set(false); this.active.set(true);
this.initPropertySources(); this.getEnvironment().validateRequiredProperties(); this.earlyApplicationEvents = new LinkedHashSet(); }
|
2. obtainFreshBeanFactory():获取BeanFactory
1 2 3 4 5 6 7 8 9 10
| protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
this.refreshBeanFactory(); return this.getBeanFactory(); }
|
3. prepareBeanFactory(beanFactory):BeanFactory的预准备
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { beanFactory.setBeanClassLoader(this.getClassLoader()); beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, this.getEnvironment())); beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this); beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader (new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); beanFactory.registerSingleton("environment", this.getEnvironment()); beanFactory.registerSingleton ("systemProperties", this.getEnvironment().getSystemProperties()); beanFactory.registerSingleton ("systemEnvironment", this.getEnvironment().getSystemEnvironment()); }
|
4. postProcessBeanFactory(beanFactory):BeanFactory准备完成后进行的后置处理工作
1 2 3
| protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { }
|
5. invokeBeanFactoryPostProcessors(beanFactory):执行BeanFactoryPostProcessor
BeanFactoryPostProcessor:在 BeanFactory 标准初始化之后执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors (beanFactory, this.getBeanFactoryPostProcessors());
beanFactory.addBeanPostProcessor (new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader (new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
|
6. registerBeanPostProcessors(beanFactory):注册 Bean 的后置处理器
1 2 3 4 5 6 7 8 9 10 11
| protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this); }
|
7. initMessageSource():初始化MessageSource组件(国际化、消息绑定、消息解析)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| protected void initMessageSource() { ConfigurableListableBeanFactory beanFactory = this.getBeanFactory(); if (beanFactory.containsLocalBean("messageSource")) { this.messageSource = (MessageSource)beanFactory.getBean("messageSource", MessageSource.class); } else { DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(this.getInternalParentMessageSource()); this.messageSource = dms; beanFactory.registerSingleton("messageSource", this.messageSource); } }
|
8. initApplicationEventMulticaster():初始化事件派发器
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| protected void initApplicationEventMulticaster() { ConfigurableListableBeanFactory beanFactory = this.getBeanFactory(); if (beanFactory.containsLocalBean("applicationEventMulticaster")) { this.applicationEventMulticaster = (ApplicationEventMulticaster)beanFactory.getBean("applicationEventMulticaster", ApplicationEventMulticaster.class); } else { this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton("applicationEventMulticaster", this.applicationEventMulticaster); } }
|
9. onRefresh():留给子容器
子类重写该方法,在容器刷新时可以自定义逻辑
10. registerListeners():将项目中的ApplicationListener注册进容器中
1 2 3 4 5 6 7 8 9
| protected void registerListeners() { String[] listenerBeanNames = this.getBeanNamesForType(ApplicationListener.class, true, false); this.getApplicationEventMulticaster(). addApplicationListenerBean(listenerBeanName); }
|
11. finishBeanFactoryInitialization(beanFactory):初始化所有剩下的单实例Bean
1 2 3 4 5
| protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
beanFactory.preInstantiateSingletons(); }
|
**beanFactory.preInstantiateSingletons()**:
获取容器中所有Bean,依次进行初始化和创建对象
获取Bean的定义信息 RootBeanDefinition
if(Bean不是抽象的、是单实例的、不是懒加载的)
:
判断是否是 FactoryBean / 是否是实现 FactoryBean 的 Bean
不是工厂Bean,利用getBean()
创建对象 (以后再深挖)
12. finishRefresh():完成BeanFactory的初始化创建工作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| protected void finishRefresh() { this.clearResourceCaches();
this.initLifecycleProcessor(); this.getLifecycleProcessor().onRefresh(); this.publishEvent((ApplicationEvent)(new ContextRefreshedEvent(this))); LiveBeansView.registerApplicationContext(this); }
|
13. 总结
Spring容器在启动时,先会保存所有注册进来的Bean的定义信息
- XML注册bean:
<bean></bean>
- 注解注册bean:
@Service
,@Controller
,@Resporties
,@Component
,@Bean
Spring会在合适的时机创建这些 bean
- 用到这个 bean 的时候,利用
getBean()
创建bean,创建好后保存在容器中
- 统一创建剩下所有 bean finishBeanFactoryInitialization()
后置处理器:
每一个 bean 创建完成后都会使用后置处理器进行处理,来增强 bean 的功能
事件驱动模型
ApplicationListener:事件监听
ApplicationEventMulticaster:事件派发