Spring管理bean的生命周期

1: bean的创建:   如果我们默认的scope配置为Singleton的话, bean的创建实在Spring容器创建的时候创建; 如果scope的配置为Prototype的话,bena的创建是在getBean的时候创建的。 同样我们还可以在<bean>的配置中配置lazy-init = ”true“是bean的创建在getBean时。

2: 我们有时候可能在bean完成之后可能想要打开一些资源。 我们可以配置init-method="init" init方法在调用了类的默认构造函数之后执行

3: 如果我们想在bean销毁时,释放一些资源。 我们可以配置destroy-method="destroy" destroy方法在bean对象销毁时执行

package cn.gbx.serviceimpl;

import cn.gbx.service.PersonService;

public class PersonServiceImpl implements PersonService {

	public PersonServiceImpl() {
System.out.println("我被实例化啦");
}
@Override
public void save() {
System.out.println("save 方法");
}
public void init() {
System.out.println("打开资源。。。");
}
public void destroy() {
System.out.println("关闭资源....");
}
}

  

<?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.5.xsd">
<bean id="personService" class="cn.gbx.serviceimpl.PersonServiceImpl" init-method="init" destroy-method="destroy" >
</bean>
</beans>

  

package cn.gbx.Junit;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.gbx.service.PersonService;
import cn.gbx.serviceimpl.PersonServiceImpl; public class SpringTest {
@Test
public void spring1() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService ps = (PersonService)ctx.getBean("personService");
ps.save();
} }

  

上一篇:hashcode详解


下一篇:CentOS随笔——关机命令