`
eric_hwp
  • 浏览: 125873 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Bean声明周期中的post-initialization和pre-destruction .

 
阅读更多

在Bean的声明周期中,有两个事件尤为重要:post-initialization和pre-destruction。

Spring提供了两种机制:interface-based和method-based,供bean签入上述事件。

所谓的post-initialization和pre-destruction,是指在bean的属性设置完毕执行的事件和在bean销毁之前执行的事件。

method-based机制:通过在BeanFactory中的配置,init-method和destory-method,通过设置这两个属性来指定要执行的回调方法。

interface-based机制:bean需要实现InitializatingBean接口和DisposableBean接口。这两个接口分别拥有afterPropertiesSet()方法和destroy()方法。这两个方法在bean初始化后和销毁前被执行。效果与method-based机制等同。

 

以下是网上流传一个例子,我在eclipse中运行了一下

package com.test;
import javax.annotation.PostConstruct; 
import javax.annotation.PreDestroy; 

import org.springframework.beans.BeansException; 
import org.springframework.beans.factory.BeanFactory; 
import org.springframework.beans.factory.BeanFactoryAware; 
import org.springframework.beans.factory.BeanNameAware; 
import org.springframework.beans.factory.DisposableBean; 
import org.springframework.beans.factory.InitializingBean; 

public class LifeCycle implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean { 

public LifeCycle() { 
System.out.println("Constructor executing"); 
} 

private String cycle; 

public void setCycle(String cycle) { 
System.out.println("Setter methods executing"); 
this.cycle = cycle; 
} 

@Override 
public void setBeanName(String beanName) { 
System.out.println("BeanNameAware.setBeanName(String beanName) executing"); 
} 

@Override 
public void setBeanFactory(BeanFactory beanFactory) throws BeansException { 
System.out.println("BeanFactoryAware.setBeanFactory(BeanFactory beanFactory) executing"); 
} 

@PostConstruct 
public void beforeBeanConstructed() { 
System.out.println("BeanPostProcessor executing (before bean constructed)"); 
} 

@Override 
public void afterPropertiesSet() throws Exception { 
System.out.println("InitializingBean.afterPropertiesSet() executing"); 
} 

public void initMethod() { 
System.out.println("InitMethod executing"); 
} 

@PreDestroy 
public void afterBeanConstructed() { 
System.out.println("BeanPostProcessor executing (after bean constructed)"); 
} 

@Override 
public void destroy() throws Exception { 
System.out.println("DisposableBean.destroy() executing"); 
} 

public void destroyMethod() { 
System.out.println("DestroyMethod executing"); 
} 

} 

 

 

<?xml version="1.0" encoding="UTF-8"?> 
	<beans xmlns="http://www.springframework.org/schema/beans" 
	  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	  xsi:schemaLocation="http://www.springframework.org/schema/beans 
	  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
	
		<bean id="lifeCycle" class="com.test.LifeCycle" init-method="initMethod" destroy-method="destroyMethod"> 
		<property name="cycle" value="Life Cycle"/> 
		</bean> 
		
		<bean id="beanPostProcessor" class="org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor"> 
		<property name="initAnnotationType" value="javax.annotation.PostConstruct"/> 
		<property name="destroyAnnotationType" value="javax.annotation.PreDestroy"/> 
		</bean> 
	
	</beans>

 

package com.test;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class LifeCycleDemo { 

	public static void main(String[] args) { 
	XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans-config.xml")); 
	
	BeanPostProcessor bpp = (BeanPostProcessor)factory.getBean("beanPostProcessor"); 
	factory.addBeanPostProcessor(bpp); 
	
	LifeCycle lifeCycle = (LifeCycle)factory.getBean("lifeCycle"); 
	
	factory.destroySingleton("lifeCycle"); 
	} 

}

 

 

最后运行结果是:
Constructor executing
Setter methods executing
BeanNameAware.setBeanName(String beanName) executing
BeanFactoryAware.setBeanFactory(BeanFactory beanFactory) executing
BeanPostProcessor executing (before bean constructed)
InitializingBean.afterPropertiesSet() executing
InitMethod executing
BeanPostProcessor executing (after bean constructed)
DisposableBean.destroy() executing
DestroyMethod executing

 注入Bean具体的实现:
具体的bean创建过程和依赖关系的注入在createBean中,这个方法在AbstractAutowireCapableBeanFactory中给出了实现:

protected Object createBean(String beanName, RootBeanDefinition
mergedBeanDefinition, Object[] args)
throws BeanCreationException {
 // Guarantee initialization of beans that the current one depends on.
 // 这里对取得当前bean的所有依赖bean,确定能够取得这些已经被确定的bean,如果没有被创建,那么这个createBean会被这些IOC
 // getbean时创建这些bean
 if (mergedBeanDefinition.getDependsOn() != null) {
  for (int i = 0; i < mergedBeanDefinition.getDependsOn().length; i++) {
   getBean(mergedBeanDefinition.getDependsOn()[i]);
  }
 }
 ........
 // 这里是实例化bean对象的地方,注意这个BeanWrapper类,是对bean操作的主要封装类
 if (instanceWrapper == null) {
  instanceWrapper = createBeanInstance(beanName, mergedBeanDefinition,args);
 }
 Object bean = instanceWrapper.getWrappedInstance();
 ......
 //这个populate方法,是对已经创建的bean实例进行依赖注入的地方,会使用到在loadBeanDefinition的时候得到的那些propertyValue来对bean进行注入。
 if (continueWithPropertyPopulation) {
  populateBean(beanName, mergedBeanDefinition, instanceWrapper);
 }
 //这里完成客户自定义的对bean的一些初始化动作
 Object originalBean = bean;
 bean = initializeBean(beanName, bean, mergedBeanDefinition);
 // Register bean as disposable, and also as dependent on specified "dependsOn"beans.
 registerDisposableBeanIfNecessary(beanName, originalBean,mergedBeanDefinition);
 return bean;
}
.........
}

 

分享到:
评论

相关推荐

    org.springframework.web.servlet-3.0.1.RELEASE-A.jar

    Error creating bean with name 'org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0' defined in ServletContext resource [/WEB-INF/springMVC-servlet.xml]: Initialization of bean failed;...

    Array-Initialization-.zip_LabVIEW 数组

    "Array-Initialization-.zip" 文件可能是一个教学资源,专为帮助用户掌握在LabVIEW中如何初始化和操作数组而设计。在这个实验室练习中,"Array Initialization .vi" 可能是一个虚拟仪器(VI)示例,演示了数组的创建...

    PCI_system-address-map-initialization

    在计算机硬件领域,PCI(Peripheral Component Interconnect)系统地址映射初始化是一个至关重要的步骤,它涉及到BIOS(基本输入输出系统)在启动过程中如何管理和分配系统内存资源给PCI设备。本文将深入探讨PCI设备...

    Spring Bean生命周期.pdf

    这使得它可以在Bean的生命周期中多个点进行干预,例如,在属性赋值之后修改属性值,这在Spring的自动注入和AOP实现中非常有用。 - BeanPostProcessor:这个接口允许在Bean初始化之前和之后进行扩展。它用于修改Bean...

    System.ComponentModel.Composition.Initialization.dll

    在实际开发中,为了更好地理解和利用System.ComponentModel.Composition.Initialization.dll,我们需要熟悉MEF的基本概念,如导入(Import)、导出(Export)、部分类(Part)以及属性导入(ImportingProperty)等。...

    Hyperparameter tuning-2.1.1-initialization初始化

    Improving Deep Neural Networks: Hyperparameter tuning, Regularization and Optimization-2.1.1-initialization初始化

    com.springsource.org.objectweb.asm-3.2.0.jar

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customAreaService' defined in class path resource [applicationContext.xml]: Initialization of bean failed;...

    c8051F340-port-initialization.rar_c8051f340_f341_tool

    c8051F340 端口初始化 Target: C8051F340, F341, F342, F343, F344, F345, F346, F347 // Tool chain: Keil // Command Line: None

    dm00104712-stm32cubemx-for-stm32-configuration-and-initialization-c-code-generation-stmicroelectronics.pdf

    STM32CubeMX是意法半导体公司(STMicroelectronics)推出的一款图形化工具,它用于STM32微控制器的配置和初始化,通过它能够生成初始化C代码。该工具属于STMCube™系列,它能够简化微控制器的配置过程,覆盖STM32的...

    Level_Set_Evolution_Without_Re-initialization

    传统的水平集方法通常需要保持水平集函数近似于符号距离函数,这通常通过周期性地重新初始化来实现,以保持稳定性和准确性。然而,重新初始化可能导致零水平集的位移,且何时、如何进行重新初始化是一个挑战。新方法...

    track-initialization.rar_radar track_tracking radar_跟踪起始_轨迹跟踪仿真_

    雷达目标跟踪中的直观法航迹起始程序,其中包含两个文件:simutrack.m和main.m。simutrack.m是目标轨迹仿真;main.m是主文件。

    Addison.Wesley.-.Imperfect.C++.Practical.Solutions.for.Real-Life.Programming.chm

    Apply the Resource Acquisition Is Initialization mechanism to a wide variety of problem domains Manage the sometimes arcane relationship between arrays and pointers Use template programming to ...

    spring-boot-reference.pdf

    Servlet Context Initialization Scanning for Servlets, Filters, and listeners 27.4.3. The ServletWebServerApplicationContext 27.4.4. Customizing Embedded Servlet Containers Programmatic Customization ...

    play-services-ads-lite-18.3.0.zip

    play-services-ads-lite-18.3.0是2019-11-23为止,最新的安卓admob sdk,用于原生安卓介入 加入工程后: ...import com.google.android.gms.ads.initialization.OnInitializationCompleteListener; 即可

    spring-boot-db-initialization-test:测试用例,显示未初始化数据库以进行测试的错误

    该项目包含一个测试,该测试查询内存中的h2数据库以确保其不为空 $ mvn test ... 2014-10-14 10:10:21.409 WARN 3435 --- [ main] o.s.b.a.jdbc.DataSourceInitializer : Could not send event to complete ...

    S-Function 的编写.rar

    使用MEX 实用工具,将C,C ,Ada,和Fortran 语言的S-Function 编译成MEX-文件,在需要的时候,它们可与其它的MEX-文件一起动态地连接到MATLAB 中。 S-Function 使用一种特殊的调用格式让你可以与Simulink 方程求解...

    initialization.dxe.rar

    bf533的initialization中需要选择的.dxe工程Init_Sdram,配置在Poject Option - initialization ,烧录LDR需要选择,要和自己所应用的实际SDRAM配置一致才能启动成功

Global site tag (gtag.js) - Google Analytics