`

Spring中Bean的初始化过程

阅读更多

在传统的Java应用中,Bean的生命周期非常简单。Java的关键词new用来实例化Bean(或许他是非序列化的)。这样就够用了。相反,Bean 的生命周期在Spring容器中更加细致。理解Spring Bean的生命周期非常重要,因为你或许要利用Spring提供的机会来订制Bean的创建过程。

1. 容器寻找Bean的定义信息并且将其实例化。
2.受用依赖注入,Spring按照Bean定义信息配置Bean的所有属性。
3.如果Bean实现了BeanNameAware接口,工厂调用Bean的setBeanName()方法传递Bean的ID。
4.如果Bean实现了BeanFactoryAware接口,工厂调用setBeanFactory()方法传入工厂自身。
5.如果BeanPostProcessor和Bean关联,那么它们的postProcessBeforeInitialzation()方法将被调用。
6.如果Bean指定了init-method方法,它将被调用。
7.最后,如果有BeanPsotProcessor和Bean关联,那么它们的postProcessAfterInitialization()方法将被调用。
    到这个时候,Bean已经可以被应用系统使用了,并且将被保留在Bean Factory中知道它不再需要。有两种方法可以把它从Bean Factory中删除掉。
1.如果Bean实现了DisposableBean接口,destory()方法被调用。
2.如果指定了订制的销毁方法,就调用这个方法。
    Bean在Spring应用上下文的生命周期与在Bean工厂中的生命周期只有一点不同,唯一不同的是,如果Bean实现了ApplicationContextAwre接口,setApplicationContext()方法被调用。

举例:(这里只是演示Bean工厂的例子)
我这里用的是spring-1.2.6,由于版本原因吧,这里演示的不是很好!
1.HelloWorld.java

Java代码 复制代码
  1. package com.spring.lifecycle;   
  2.   
  3. import org.springframework.beans.BeansException;   
  4. import org.springframework.beans.factory.BeanFactory;   
  5. import org.springframework.beans.factory.BeanFactoryAware;   
  6. import org.springframework.beans.factory.BeanNameAware;   
  7. import org.springframework.beans.factory.DisposableBean;   
  8. import org.springframework.beans.factory.InitializingBean;   
  9. import org.springframework.beans.factory.config.BeanPostProcessor;   
  10.   
  11. public class HelloWorld implements BeanNameAware,BeanFactoryAware, BeanPostProcessor,InitializingBean,DisposableBean{   
  12.   
  13.     private String hello;   
  14.   
  15.     public void setBeanName(String arg0) {   
  16.         System.out.println("调用BeanNameAware的setBeanName()..." );   
  17.     }   
  18.   
  19.     public String getHello() {   
  20.         return hello;   
  21.     }   
  22.   
  23.     public void setHello(String hello) {   
  24.         this.hello = hello;   
  25.         System.out.println("调用setHello()..." );   
  26.     }   
  27.   
  28.     public void customInit() {   
  29.         System.out.println("调用customInit()...");   
  30.     }   
  31.   
  32.     public void customDestroy() {   
  33.         System.out.println("调用customDestroy()...");   
  34.     }   
  35.   
  36.     public Object postProcessAfterInitialization(Object arg0, String arg1)   
  37.             throws BeansException {   
  38.         System.out.println("调用BeanPostProcessor的postProcessAfterInitialization()...");   
  39.         return null;   
  40.     }   
  41.   
  42.     public Object postProcessBeforeInitialization(Object arg0, String arg1)   
  43.             throws BeansException {   
  44.         System.out.println("调用BeanPostProcessor的postProcessBeforeInitialization()...");   
  45.         return null;   
  46.     }   
  47.   
  48.     public void destroy() throws Exception {   
  49.         System.out.println("调用DisposableBean的destory()...");   
  50.     }   
  51.   
  52.     public void afterPropertiesSet() throws Exception {   
  53.         System.out.println("调用InitializingBean的afterPropertiesSet()...");   
  54.     }   
  55.   
  56.     public void setBeanFactory(BeanFactory arg0) throws BeansException {   
  57.         System.out.println("调用BeanFactoryAware的setBeanFactory()...");   
  58.     }   
  59. }  
package com.spring.lifecycle;

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;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class HelloWorld implements BeanNameAware,BeanFactoryAware, BeanPostProcessor,InitializingBean,DisposableBean{

	private String hello;

	public void setBeanName(String arg0) {
		System.out.println("调用BeanNameAware的setBeanName()..." );
	}

	public String getHello() {
		return hello;
	}

	public void setHello(String hello) {
		this.hello = hello;
		System.out.println("调用setHello()..." );
	}

	public void customInit() {
		System.out.println("调用customInit()...");
	}

	public void customDestroy() {
		System.out.println("调用customDestroy()...");
	}

	public Object postProcessAfterInitialization(Object arg0, String arg1)
			throws BeansException {
		System.out.println("调用BeanPostProcessor的postProcessAfterInitialization()...");
		return null;
	}

	public Object postProcessBeforeInitialization(Object arg0, String arg1)
			throws BeansException {
		System.out.println("调用BeanPostProcessor的postProcessBeforeInitialization()...");
		return null;
	}

	public void destroy() throws Exception {
		System.out.println("调用DisposableBean的destory()...");
	}

	public void afterPropertiesSet() throws Exception {
		System.out.println("调用InitializingBean的afterPropertiesSet()...");
	}

	public void setBeanFactory(BeanFactory arg0) throws BeansException {
		System.out.println("调用BeanFactoryAware的setBeanFactory()...");
	}
}


2.测试程序

Java代码 复制代码
  1. package com.spring.springtest;   
  2.   
  3. import junit.framework.TestCase;   
  4.   
  5. import org.springframework.beans.factory.BeanFactory;   
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;   
  7.   
  8. import com.spring.lifecycle.HelloWorld;   
  9.   
  10. public class TestLifeCycle extends TestCase {   
  11.     private BeanFactory bf;   
  12.   
  13.     protected void setUp() throws Exception {   
  14.         bf = new ClassPathXmlApplicationContext("applicationContext.xml");   
  15.     }   
  16.   
  17.     public void testLifeCycle() throws Exception {   
  18.         HelloWorld hello = (HelloWorld) bf.getBean("helloWorld");   
  19.         assertEquals("hello world!", hello.getHello());   
  20.         hello.destroy();   
  21.     }   
  22. }  
package com.spring.springtest;

import junit.framework.TestCase;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.lifecycle.HelloWorld;

public class TestLifeCycle extends TestCase {
	private BeanFactory bf;

	protected void setUp() throws Exception {
		bf = new ClassPathXmlApplicationContext("applicationContext.xml");
	}

	public void testLifeCycle() throws Exception {
		HelloWorld hello = (HelloWorld) bf.getBean("helloWorld");
		assertEquals("hello world!", hello.getHello());
		hello.destroy();
	}
}


3.applicationContext.xml

Xml代码 复制代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
  3. <beans>  
  4.     <bean id="helloWorld" class="com.spring.lifecycle.HelloWorld"  
  5.         init-method="customInit" destroy-method="customDestroy">  
  6.         <property name="hello" value="hello world!"></property>  
  7.     </bean>  
  8. </beans>  
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean id="helloWorld" class="com.spring.lifecycle.HelloWorld"
		init-method="customInit" destroy-method="customDestroy">
		<property name="hello" value="hello world!"></property>
	</bean>
</beans>


4.运行结果:

引用
调用setHello()...
调用BeanNameAware的setBeanName()...
调用BeanFactoryAware的setBeanFactory()...
调用InitializingBean的afterPropertiesSet()...
调用customInit()...
调用DisposableBean的destory()...
2.
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="life" name="life_name" class="com.open.bean.Life"
        init-method="init">
        <property name="msg" value="lifexxxx"/>
    </bean>   
    <bean id="processor" class="com.open.bean.BeanPostProcessorImp"/>
    <bean id="counter" class="com.open.bean.BeanCounter"/>
</beans>测试类 package com.open.bean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext cx=
            new ClassPathXmlApplicationContext("bean.xml");
         Life life=(Life)cx.getBean("life");    
    }
}    输出结果 类的数量=3
msg=null
构造函数
setBeanName
setBeanFactory
postProcessBeforeInitialization
afterPropertiesSet
初始化
postProcessAfterInitialization解释:
调用BeanFactoryPostProcessor接口的postProcessBeanFactory方法
-->实例化,调用构造函数-->设置属性值
-->调用BeanNameAware的setBeanName()方法
-->调用BeanFactoryAware接口的setBeanFactory
-->调用BeanPostProcessor接口的postProcessBeforeInitialization()
-->调用InitializingBean接口的afterPropertiesSet()
-->调用bean.xml中制定的init-method指定init()方法
-->调用BeanPostProcessor接口的postProcessAfterInitialization()
容器关闭
-->DisposableBean接口的destroy()
-->调用bean.xml中制定的destroy-method指定的go()方法
分享到:
评论

相关推荐

    详解Spring 中如何控制2个bean中的初始化顺序

    Spring 中控制 2 个 bean 的初始化顺序 在 Spring 框架中,控制多个 bean 的初始化顺序是一个常见的问题。本篇文章将详细介绍如何控制 2 个 bean 的初始化顺序,提供了多种实现方式,并分析了每种方式的优缺。 ...

    Spring Bean创建初始化流程.docx

    9. **Bean初始化**: 最后,`initializeBean(beanName, exposedObject, mbd)`对创建好的Bean进行初始化,包括调用初始化方法(如果有`@PostConstruct`注解的方法),以及执行AOP代理等操作。 整个流程中,Spring...

    Spring bean初始化及销毁你必须要掌握的回调方法.docx

    下面将详细介绍如何通过不同方式定义Spring Bean的初始化和销毁回调方法。 **初始化回调方法** 1. **@PostConstruct注解** 这个Java标准注解用于标记一个方法,该方法将在对象完全构造后但在业务逻辑执行前被调用...

    Spring Bean的初始化和销毁实例详解

    Spring Bean的初始化和销毁是Spring框架中一个非常重要的概念,它们都是Bean生命周期中不可或缺的一部分。在Spring框架中,我们可以使用多种方式来控制Bean的初始化和销毁,以下就Spring Bean的初始化和销毁进行详细...

    Spring实例化Bean顺序

    在Spring框架中,Bean的实例化顺序是一个关键概念,它...在实际开发中,应谨慎处理Bean的实例化顺序,以避免不必要的初始化问题和依赖循环。通过合理利用Spring提供的工具和机制,可以更好地控制和管理Bean的生命周期。

    springBean加载过程源码解析文档,附有代码类名和行数

    Spring Bean 加载过程是 Spring 框架中最核心的部分之一,涉及到 ApplicationContext 的初始化、Bean 的加载和注册等过程。在 Spring Boot 应用程序中,SpringApplication 负责加载和管理 Bean。 SpringApplication...

    spring的bean加载顺序样例项目

    在Spring框架中,Bean的加载顺序是一个重要的概念,它涉及到Spring容器如何管理和初始化Bean的过程。在"spring的bean加载顺序样例项目"中,我们可以通过分析和实验来深入理解这一主题。下面将详细阐述Spring Bean的...

    浅谈spring容器中bean的初始化

    本文将深入探讨Spring容器中Bean的初始化过程。 首先,Spring容器根据XML配置文件(如`applicationContext.xml`)来解析Bean的定义。在示例中,我们定义了一个名为`people`的Bean,它对应于`People`类。默认情况下...

    Spring Bean 加载顺序 .

    7. **Bean初始化**: 实例化完成后,Spring会执行Bean的初始化方法,包括调用`@PostConstruct`注解的方法。同时,如果Bean实现了InitializingBean接口,其`afterPropertiesSet()`方法也会被调用。 8. **初始化后...

    Spring源码学习六:bean初始化1

    在本篇文章中,我们将深入探讨Spring源码中关于Bean初始化的过程,特别是`finishBeanFactoryInitialization()`方法和`preInstantiateSingletons()`方法。 首先,`finishBeanFactoryInitialization(Confi‌...

    初始化后可访问Spring管理的Bean

    初始化后可访问Spring管理的Bean

    spring bean XML配置入门

    一旦XML配置加载到Spring容器中,容器将根据配置创建Bean实例,并按照定义进行初始化、依赖注入,最后完成Bean的生命周期管理。 10. **实践操作**: 在实际开发中,我们可以使用Eclipse的Spring插件来简化Bean...

    详解Spring中Bean的生命周期和作用域及实现方式

    在整个生命周期中,Spring提供了多种方式来实现Bean的初始化,例如使用init-method参数、InitializingBean接口等。 二、Bean的作用域 Bean的作用域是指Bean的生命周期和可用性。Spring框架提供了多种作用域,例如 ...

    spring bean的生命周期

    - **XML配置**:在传统的Spring应用中,Bean的定义通常写在XML配置文件中,如`springbean-xml`中的配置。 - **注解配置**:使用`@Component`,`@Service`,`@Repository`和`@Controller`注解标记类,配合`@...

    spring中的bean

    在Spring中,Bean通常代表应用程序中的一个对象,这些对象由Spring容器(ApplicationContext)管理,包括创建、初始化、装配和销毁。Bean可以通过XML配置文件、注解或者Java配置类进行定义。 1. **Bean的定义**:在...

    详解Spring简单容器中的Bean基本加载过程

    Spring 简单容器中的 Bean 基本加载过程 Spring 框架是 Java 企业级应用程序的核心框架之一,它提供了一个 IOC(Inverse of Control,控制反转)容器,用于管理应用程序中的对象。Spring IOC 容器的核心是 ...

    Spring框架中Bean的生命周期 Spring中Bean有几种作用域

    在Spring框架中,Bean的生命周期管理和作用域是其核心特性之一,它们对于理解Spring如何管理对象的创建、初始化、使用以及销毁至关重要。首先,我们来深入探讨Bean的生命周期。 Spring中的Bean生命周期主要分为两个...

    spring容器初始化bean和销毁bean之前进行一些操作的方法

    此外,Spring提供了BeanPostProcessor接口,允许我们在Bean初始化前后进行自定义处理。通过实现`postProcessBeforeInitialization()`和`postProcessAfterInitialization()`方法,可以在Bean实例化和初始化之后进行...

    Spring 源码分析(Bean的初始化)

    在整个初始化过程中,Spring通过一系列的回调接口和事件机制,使得开发者可以自定义Bean的生命周期行为,比如添加初始化或销毁方法,实现Bean的自定义初始化逻辑。 总结起来,Spring的Bean初始化是一个复杂而精细的...

Global site tag (gtag.js) - Google Analytics