打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Spring中Bean的生命周期(转)
一、Bean的定义
Spring通常通过配置文件定义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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="HelloWorld" class="com.pqf.beans.HelloWorld">
<property name="msg">
<value>HelloWorld</value>
</property>
</bean>
</beans>
这个配置文件就定义了一个标识为 HelloWorld 的Bean。在一个配置文档中可以定义多个Bean。
二、Bean的初始化
有两种方式初始化Bean。
1、在配置文档中通过指定init-method 属性来完成
在Bean的类中实现一个初始化Bean属性的方法,如init(),如:
public class HelloWorld{
public String msg=null;
public Date date=null;
public void init() {
msg="HelloWorld";
date=new Date();
}
......
}
然后,在配置文件中设置init-mothod属性:
<bean id="HelloWorld" class="com.pqf.beans.HelloWorld" init-mothod="init" >
</bean>
2、实现 org.springframwork.beans.factory.InitializingBean接口
Bean实现InitializingBean接口,并且增加 afterPropertiesSet() 方法:
public class HelloWorld implement InitializingBean {
public String msg=null;
public Date date=null;
public void afterPropertiesSet() {
msg="向全世界问好!";
date=new Date();
}
......
}
那么,当这个Bean的所有属性被Spring的BeanFactory设置完后,会自动调用afterPropertiesSet()方法对Bean进行初始化,于是,配置文件就不用指定 init-method属性了。
三、Bean的调用
有三种方式可以得到Bean并进行调用:
1、使用BeanWrapper
HelloWorld hw=new HelloWorld();
BeanWrapper bw=new BeanWrapperImpl(hw);
bw.setPropertyvalue("msg","HelloWorld");
system.out.println(bw.getPropertyCalue("msg"));
2、使用BeanFactory
InputStream is=new FileInputStream("config.xml");
XmlBeanFactory factory=new XmlBeanFactory(is);
HelloWorld hw=(HelloWorld) factory.getBean("HelloWorld");
system.out.println(hw.getMsg());
3、使用ApplicationConttext
ApplicationContext actx=new FleSystemXmlApplicationContext("config.xml");
HelloWorld hw=(HelloWorld) actx.getBean("HelloWorld");
System.out.println(hw.getMsg());
四、Bean的销毁
1、使用配置文件中的 destory-method 属性
与初始化属性 init-methods类似,在Bean的类中实现一个撤销Bean的方法,然后在配置文件中通过 destory-method指定,那么当bean销毁时,Spring将自动调用指定的销毁方法。
2、实现 org.springframwork.bean.factory.DisposebleBean接口
如果实现了DisposebleBean接口,那么Spring将自动调用bean中的Destory方法进行销毁,所以,Bean中必须提供Destory方法。
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
spring配置文件中bean元素的各个属性
SpringBean初始化过程
Spring管理bean机制
Bean自动装配的5种模式
「Spring认证」Spring Bean 后处理器
深入理解微服务架构spring的各个知识点(面试必问知识点)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服