容器什么时候实力化我们的业务bean呢? 我们可以写一个简单的测试方法,给业务bean增加一个不带参数的构造方法,看看容器是什么时候实例化我们的业务bean的.
PersionServiceBean.java
package cn.com.xinli.service.impl;
import org.apache.log4j.Logger;
import cn.com.xinli.service.PersionSevice;
public class PersionServiceBean implements PersionSevice
{
Logger log=Logger.getLogger(PersionServiceBean.class);
public PersionServiceBean()
{
log.info("我被实例化了");
}
public void save()
{
log.info("我是save()方法!");
}
}
运行:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
//PersionSevice ps=(PersionSevice)ctx.getBean("persionServiceBean");
//log.info(ps);
//ps.save();
日志:
2009-05-24 17:41:04,968 INFO (PersionServiceBean.java:13) - 我被实例化了
可见在启动容器的时候spring就完成业务bean的实例化了,如果我们不想在容器启动的时候实例化我们的业务bean,我们可以指定 lazy-init="true"
对于 scope 为:prototype (原型)的 bean, 在spring 容器启动的时候并不被实例化,不管你是不是指定lazy-init="false" ,它只有在使用的时候才初始化
指定Bean的初始化方法和销毁方法
package cn.com.xinli.service.impl;
import org.apache.log4j.Logger;
import cn.com.xinli.service.PersionSevice;
public class PersionServiceBean implements PersionSevice
{
Logger log=Logger.getLogger(PersionServiceBean.class);
public void init()
{
log.info("初始化资源");
}
public PersionServiceBean()
{
log.info("我被实例化了");
}
public void save()
{
log.info("我是save()方法!");
}
public void destory()
{
log.info("释放资源");
}
}
在 <bean id="persionServiceBean" class="cn.com.xinli.service.impl.PersionServiceBean" init-method="init" destroy-method="destory"></bean>
测试:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersionSevice ps=(PersionSevice)ctx.getBean("persionServiceBean");
ctx.close();
打印:
2009-05-24 19:24:14,578 INFO (PersionServiceBean.java:17) - 我被实例化了
2009-05-24 19:24:14,687 INFO (PersionServiceBean.java:13) - 初始化资源
2009-05-24 19:24:14,687 INFO (AbstractApplicationContext.java:815) - Closing org.springframework.context.support.ClassPathXmlApplicationContext@7b7072: display name [org.springframework.context.support.ClassPathXmlApplicationContext@7b7072]; startup date [Sun May 24 19:24:13 CST 2009]; root of context hierarchy
2009-05-24 19:24:14,687 INFO (DefaultSingletonBeanRegistry.java:421) - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@bfc8e0: defining beans [persionServiceBean]; root of factory hierarchy
2009-05-24 19:24:14,703 INFO (PersionServiceBean.java:26) - 释放资源