Bean生命周期
以BeanFactory为例,说明一个Bean的生命周期活动
Spring上下文中的Bean也类似,如下
1、实例化一个Bean--也就是我们常说的new;
2、按照Spring上下文对实例化的Bean进行配置--也就是IOC注入;
3、如果这个Bean已经实现了BeanNameAware接口,会调用它实现的setBeanName(String)方法,此处传递的就是Spring配置文件中Bean的id值
4、如果这个Bean已经实现了BeanFactoryAware接口,会调用它实现的setBeanFactory(setBeanFactory(BeanFactory)传递的是Spring工厂自身(可以用这个方式来获取其它Bean,只需在Spring配置文件中配置一个普通的Bean就可以);
5、如果这个Bean已经实现了ApplicationContextAware接口,会调用setApplicationContext(ApplicationContext)方法,传入Spring上下文(同样这个方式也可以实现步骤4的内容,但比4更好,因为ApplicationContext是BeanFactory的子接口,有更多的实现方法);
如果对应的bean的方法中带有@PostConstruct方法,且spring的配置文件中开启注解扫描,将调用对应的方法
6、如果这个Bean关联了BeanPostProcessor接口,将会调用postProcessBeforeInitialization(Object obj, String s)方法,BeanPostProcessor经常被用作是Bean内容的更改,并且由于这个是在Bean初始化结束时调用那个的方法,也可以被应用于内存或缓存技术;
7、如果Bean实现了initailingBean接口会调用其afterPropertiesSet()配置的初始化方法,在bean的标签中添加init-method属性,将调用对应的初始化方法。
8、如果这个Bean关联了BeanPostProcessor接口,将会调用postProcessAfterInitialization(Object obj, String s)方法;
注:以上工作完成以后就可以应用这个Bean了,那这个Bean是一个Singleton的,所以一般情况下我们调用同一个id的Bean会是在内容地址相同的实例,当然在Spring配置文件中也可以配置非Singleton,这里我们不做赘述。
若bean中带有对应的@PreDestory方法,将调用对应的方法。
9、当Bean不再需要时,会经过清理阶段,如果Bean实现了DisposableBean这个接口,会调用那个其实现的destroy()方法;
10、最后,如果这个Bean的Spring配置中配置了destroy-method属性,会自动调用其配置的销毁方法。destroyMethod()方法,注意,这个方法是不带参数的

如果使用ApplicationContext来维护一个Bean的生命周期,则基本上与上边的流程相同,只不过在执行BeanNameAware的setBeanName()后,若有Bean类实现了org.springframework.context.ApplicationContextAware接口,则执行其setApplicationContext()方法,然后再进行BeanPostProcessors的processBeforeInitialization()
Spring容器初始化 ===================================== 调用GiraffeService无参构造函数 GiraffeService中利用set方法设置属性值 调用setBeanName:: Bean Name defined in context=giraffeService 调用setBeanClassLoader,ClassLoader Name = sun.misc.Launcher$AppClassLoader 调用setBeanFactory,setBeanFactory:: giraffe bean singleton=true 调用setEnvironment 调用setResourceLoader:: Resource File Name=spring-beans.xml 调用setApplicationEventPublisher 调用setApplicationContext:: Bean Definition Names=[giraffeService, org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#0, com.giraffe.spring.service.GiraffeServicePostProcessor#0] 执行BeanPostProcessor的postProcessBeforeInitialization方法,beanName=giraffeService 调用PostConstruct注解标注的方法 执行InitializingBean接口的afterPropertiesSet方法 执行配置的init-method 执行BeanPostProcessor的postProcessAfterInitialization方法,beanName=giraffeService Spring容器初始化完毕 ===================================== 从容器中获取Bean giraffe Name=李光洙 ===================================== 调用preDestroy注解标注的方法 执行DisposableBean接口的destroy方法 执行配置的destroy-method Spring容器关闭
参考:
https://www.cnblogs.com/kenshinobiy/p/4652008.html
浙公网安备 33010602011771号