`
feiliboos
  • 浏览: 667084 次
文章分类
社区版块
存档分类
最新评论

Spring管理的Bean的生命周期

 
阅读更多

bean配置如下:

<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean" scope ="singleton" lazy-init ="false" init-method ="init" destroy-method ="destory"></bean>

bean里实现的方法

public class PersonServiceBean implements PersonService{

public void init() {
System.out.println("初始化");
}
public PersonServiceBean(){
System.out.println("我被实例化了");
}
public void save() {
System.out.println("我是save()方法");
}
public void destory() {
System.out.println("开闭打开的资源");
}
}

junit测试类如下:

public void instanceSpring(){
AbstractXmlApplicationContext ctx=new ClassPathXmlApplicationContext("bean.xml");
// PersonServiceBean ps=(PersonServiceBean) ctx.getBean("personService");
ctx.close();
}

1.spring默认的情况下是创建容器时就实例化了bean, 但如果scope=“prototype ”时则是在 调用getBean方法是才实例化。

2.为了解决这一方面的问题,spring引入了lazy-init属性,当scope为默认,lazy-init=“true”(默认为false)时则实例化bean就会被

延迟,等到调用getBean时才实例化。

3.至于init-methoddestroy-method 属性则是初始化bean和销毁bean所用到的,比如可在初始化bean中实现数据库的连接 等。

4.ctx.close() 是关闭容器,也会关闭bean,调用destroy-method 属性了。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics