Spring中Bean的生命周期

来源:互联网 发布:linux查核指令 编辑:程序博客网 时间:2024/06/11 23:31

一. Bean的定义

我们知道servlet生命周期分为四个阶段(实例化, 初始化, 就绪/调用, 销毁)具体可参考上一篇博客servlet生命周期

同样对于Spring容器管理的bean也存在生命周期的概念

在Spring中, Bean的生命周期包括Bean的定义,初始化,使用,销毁4个阶段

在Spring中,通常是通过配置文档的方式来定义Bean的,在一个 配置文档中,可以定义多个Bean


二.Bean的初始化

SpringBean初始化有两种方式:

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

<bean id="userServiceImpl"class="com.shsxt.service.impl.UserServiceImpl" init-method="init" >


2.实现org.springframework.beans.factory.InitializingBean接口

package com.yonyou.controller;import javax.annotation.Resource;import org.springframework.beans.factory.InitializingBean;import org.springframework.stereotype.Controller;import com.yonyou.model.Result;import com.yonyou.service.UserService;@Controllerpublic class UserController implements InitializingBean{@Resourceprivate UserService userService=new UserService();public Result userLogin(String userName,String userPwd){return userService.userLoginCheck(userName, userPwd);}public void afterPropertiesSet() throws Exception {System.out.println("Spring中Bean初始化方法");}}


Bean对象实例化过程是在spring容器初始化时被实例化的,但也不是不可改变的,可以通过 lazy-init=”true” 属性延迟bean对象的初始化操作,此时再调用getbean 方法时才会进行bean的初始化操作


3.Bean的使用

(1)使用BeanFactory

(2)使用ApplicationContext


4.Bean的销毁

实现销毁方式(spring容器会维护bean对象的管理,可以指定bean对象的销毁所要执行的方法)

<bean id="userServiceImpl"class="com.shsxt.service.impl.UserServiceImpl" init-method="init" destroy-method="destroy"> </bean>


通过AbstractApplicationContext 对象,调用其close方法实现bean的销毁过程。

AbstractApplicationContext ctx=new ClassPathXmlApplicationContext("spring-application.xml"); ctx.close();







原创粉丝点击