您的位置:首页 > 编程语言 > Java开发

Spring Bean生命周期

2015-07-15 16:47 162 查看
Bean初始化过程已经Spring彻底收拾了,无法人为干预。

Spring入口保留两个回调方法

回调方法:定义或完成一定的功能,通过提供回调/server/上层容器调用的方法,叫做回调方法。

Bean类

public class Bean1 {
public Bean1() {
//System.out.println("bean1...构造方法");
}
public void show(){
System.out.println("bean1...方法");
}
//定义一个方法。在Bean创建时,运行
public void init(){
System.out.println("打印init");
}
//定义一个方法,在Bean销毁时,运行
public void destory(){
System.out.println("打印销毁");
}
}


调用

public static void main(String[] args) {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(
"applicatioContext.xml");
ac.getBean("bean4");
ac.close();
}


配置文件

<!-- bean的生命周期控制 -->
<!-- init-method:指定创建bean时相应的运行方法 -->
<!-- destroy-method:指定销毁Bean时相应的运行方法 -->
<bean id="bean4" class="com.hao947.bean.Bean1"
init-method="init"
destroy-method="destory"
></bean>


注意:

Bean的创建时在新建该对象时。完毕,Bean的销毁是在容器被销毁或关闭之前完毕

关闭容器:使用ClassPathXmlApplicationContext对象来完毕 ctx.close()

Bean的销毁仅仅能针对于单例对象,而不能应用于非单例对象

非单身Bean由该对象的恢复JVM完成——GC
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: