《Spring从入门到精通》学习之 Bean的生命周期

在spring中,bean的生命周期包括 bean的定义,bean的初始化,bean的使用和bean的销毁4个阶段。

 

1.bean的定义

一般是通过配置文档的方式来定义bean。例子如下

 

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

 

 <bean id="helloWorld" class="jp.co.xiehl.learn.ch2.action.HelloWorld" depends-on="date">
   <property name="msg">
     <value>HelloWorld</value>
   </property>
   <property name="date">
     <ref bean="date"/>
   </property>
 </bean>
 
 <bean id="date" class="java.util.Date"></bean>


 <bean id="searchUserService" class="jp.co.xiehl.service.impl.SearchUserServiceImpl" depends-on="tuserDao">
    <property name="tuserDao" ref="tuserDao" />
 </bean>
 
 
 <!-- DAO OBJECT DEFINITIONS -->
 <bean id="tuserDao" class="jp.co.xiehl.dao.impl.TuserDaoImpl"></bean>
</beans>

 

2.bean的初始化

在spring中,bean的初始化有2种方式

・在配置文档中通过指定init-method属性来完成。

・实现org.springframework.beans.factory.InitializingBean接口。

 

如果一个bean实现了上述接口,则它的所有必须的属性被BeanFactory设置后,会自动执行它的afterPropertiesSet()方法。

 

接口源码

public abstract interface org.springframework.beans.factory.InitializingBean {
 
  // Method descriptor #7 ()V
  public abstract void afterPropertiesSet() throws java.lang.Exception;
}

 

下面举例说明这2种实现方式

第一种实现方式,通过在配置文档中指定init-method属性来完成。

步骤 在类中增加init方法-->修改配置文件-->测试。

在类中增加init方法

 public void init() {
  System.out.println("Bean HelloWorld is initialized");
 }

 

修改配置文件

 <bean id="helloWorld" class="jp.co.xiehl.learn.ch2.action.HelloWorld" depends-on="date" init-method="init">
   <property name="msg">
     <value>HelloWorld</value>
   </property>
   <property name="date">
     <ref bean="date"/>
   </property>
 </bean>

 

测试

情報: Bean factory for application context [org.springframework.web.context.support.XmlWebApplicationContext@24ea85]: org.springframework.beans.factory.support.DefaultListableBeanFactory@11f2158
2010/04/26 14:51:41 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
情報: Pre-instantiating singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@11f2158: defining beans [helloWorld,date,searchUserService,tuserDao]; root of factory hierarchy
Bean HelloWorld is initialized--->在tomcat启动时,该bean被初始化。
125 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.5.0-Final
125 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found

 

第二种方式 实现org.springframework.beans.factory.InitializingBean接口。

思路是

让HelloWorld类实现该接口,增加一个方法afterPropertiesSet用来初始化。测试

 @Override
 public void afterPropertiesSet() throws Exception {
  System.out.println("Bean [HelloWorld] is initialized by method afterPropertiesSet");
  
 }

 

结果:

2010/04/26 15:35:21 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
情報: Bean factory for application context [org.springframework.web.context.support.XmlWebApplicationContext@a50da4]: org.springframework.beans.factory.support.DefaultListableBeanFactory@1a503f
2010/04/26 15:35:21 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
情報: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1a503f: defining beans [helloWorld,date,searchUserService,tuserDao]; root of factory hierarchy
Bean [HelloWorld] is initialized by method afterPropertiesSet--->在tomcat启动时,该bean被初始化。
94 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.5.0-Final
94 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found

 

 

结论:以上2种方式结果是一样的,但是第一种方式却没有把代码耦合于Spring。所以推荐使用第一种方式。

3.bean的使用

spring中,bean的使用有3种方式

第一种 使用BeanWrapper.实例代码如下

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

HelloWorld hello = new HelloWorld();
BeanWrapper bw = new BeanWrapperImpl(hello);
bw.setPropertyValue("msg", "Hello BeanWrapper");
System.out.println("BeanWrapper:msg="+bw.getPropertyValue("msg"));

执行结果

情報: Starting Coyote AJP/1.3 on ajp-8009
2010/04/26 15:47:51 org.apache.catalina.startup.Catalina start
情報: Server startup in 11855 ms
BeanWrapper:msg=Hello BeanWrapper

第二种方式 使用BeanFactory

 ClassPathResource  res = new ClassPathResource ("config.xml");
 XmlBeanFactory factory = new XmlBeanFactory(res);
 HelloWorld hello = (HelloWorld)factory.getBean("helloWorld");

第三种方式 使用ApplicationContext

 ApplicationContext ac = new FileSystemXmlApplicationContext("config.xml");
 HelloWorld hello = (HelloWorld)ac.getBean("helloWorld");

4.bean的销毁

spring中bean的销毁有2种方式

・ 在配置文档中,通过指定destroy-method属性来完成。

・ 实现org.springframework.beans.factory.DisposableBean接口

如果一个bean实现了该接口,则会自动执行它的destroy方法。

第一种方式

bean中增加cleanup方法--修改配置文件--测试

bean中增加cleanup方法

 public void cleanup() {
  System.out.println("Bean[HelloWorld was destroyed]");
 }

修改配置文件

 <bean id="helloWorld" class="jp.co.xiehl.learn.ch2.action.HelloWorld" depends-on="date" destroy-method="cleanup">
   <property name="msg">
     <value>HelloWorld</value>
   </property>
   <property name="date">
     <ref bean="date"/>
   </property>
 </bean>

测试

2010/04/26 16:23:16 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
情報: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@191f022: defining beans [helloWorld,date,searchUserService,tuserDao]; root of factory hierarchy
Bean[HelloWorld was destroyed]--->tomcat停止时,该方法被执行。
2010/04/26 16:23:20 org.apache.coyote.http11.Http11AprProtocol destroy

第二种方式 实现org.springframework.beans.factory.DisposableBean接口

实现org.springframework.beans.factory.DisposableBean接口。实现接口中的destroy方法。测试。

public class HelloWorld implements
 org.springframework.beans.factory.InitializingBean,
 org.springframework.beans.factory.DisposableBean{


 ......

 ......  
  @Override
  public void afterPropertiesSet() throws Exception {
  System.out.println("Bean[HelloWorld was Initialized]");
   
  }
 
  @Override
 public void destroy() throws Exception {
   System.out.println("Bean[HelloWorld was destroyed]");
 }

 

}

 

测试

2010/04/26 16:23:16 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
情報: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@191f022: defining beans [helloWorld,date,searchUserService,tuserDao]; root of factory hierarchy
Bean[HelloWorld was destroyed]--->tomcat停止时,该方法被执行。
2010/04/26 16:23:20 org.apache.coyote.http11.Http11AprProtocol destroy

 

 

结论:以上2种方式结果是一样的,但是第一种方式却没有把代码耦合于Spring。所以推荐使用第一种方式。

                                 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值