Spring2.5 管理的Bean的生命周期

Spring 2.5 Bean 的生命周期


初始化
init-method="指定bean类定义的初始方法"

销毁

destroy-method="指定bean类定义的销毁方法"

bean的实例构造:
bean的实例化如果<bean scope="singleton"/>是默认单例,那么会在Spring容器启动时就实例化,

如果scope非单例,那么会在调用这个bean时才初化,如果想要 scope="singleton"时,调用时再实例化,可以配置延迟实例化属性 lazy-init="true" false 则不延迟实例,

------------------------------------------------------

代码样例:



package test.service;

public interface PersonService {

public void save();

}


package test.service.impl;

import test.service.PersonService;


public class PersonServiceBean implements PersonService {
public PersonServiceBean(){
System.out.println("构造");
}
public void init(){
System.out.println(this.getClass().getName() + " 我被初始化了");
}



public void save(){
System.out.println("sava function");
}

public void destroy(){
System.out.println(this.getClass().getName() + " 我被销毁了");
}
}


package junit.test;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import test.service.PersonService;

//测试类
public class SpringTest {

@BeforeClass
public static void setUpBeforeClass() throws Exception{

}
@Test public void instanceSpring(){
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService p = (PersonService) ctx.getBean("personService");//get bean
p.save();//调用方法
ctx.close();//关闭spring容器,这里测试destroy属性
}


}

//配置文件
<?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="personService" class="test.service.impl.PersonServiceBean" scope="singleton" lazy-init="true" init-method="init" destroy-method="destroy"></bean>

</beans>

// scope="singleton" bean为单例,这里设置scope默认就是单例
// lazy-init="true" 表明在getBean时才实例化这个bean
// init-method="init" 调用init()方法初始化这个bean 此方法是自定义也可以是其他已有的

// destroy-method="destroy" 调用定义的destroy方法来销毁bean,须调用AbstractApplicationContext下面的close方法,才会执行,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值