一.Bean在什么时候被实例化的?
1.在单例作用域(Singleton)情况下,即默认情况下,Bean的实例化是在Spring容器被实例化的时候,就被实例化了。
2.在scope="prototype"时,Bean 是在我们调用ctx.getBean("xxx")方法时才被实例化的。
二.延迟加载
[quote]<bean id=.... lazy-init="true"></bean>[/quote]
在延迟加载的情况下,bean 只有在ctx.getBean("xxx")的时候才会被实例化。
[quote]
<beans ... default-lazy-init="true"></bean>
表示在此配置文件中的所有bean都延迟加载
[/quote]
PS:延迟加载一般不用,因为我们希望在应用启动时就可以根据日志查看Bean 实例化是否正常,而不是在应用运行期间才发现Bean实例化问题。
三.指定bean初始化方法
[quote]<bean id=... init-method="init"></bean>[/quote]
四.指定bean的销毁方法
[quote]<bean id=... destroy-method="destory"></bean>[/quote]
1.在单例作用域(Singleton)情况下,即默认情况下,Bean的实例化是在Spring容器被实例化的时候,就被实例化了。
2.在scope="prototype"时,Bean 是在我们调用ctx.getBean("xxx")方法时才被实例化的。
二.延迟加载
[quote]<bean id=.... lazy-init="true"></bean>[/quote]
在延迟加载的情况下,bean 只有在ctx.getBean("xxx")的时候才会被实例化。
[quote]
<beans ... default-lazy-init="true"></bean>
表示在此配置文件中的所有bean都延迟加载
[/quote]
PS:延迟加载一般不用,因为我们希望在应用启动时就可以根据日志查看Bean 实例化是否正常,而不是在应用运行期间才发现Bean实例化问题。
三.指定bean初始化方法
[quote]<bean id=... init-method="init"></bean>[/quote]
四.指定bean的销毁方法
[quote]<bean id=... destroy-method="destory"></bean>[/quote]
<bean id="personService" class="com.spring.service.impl.PersonServiceBean" init-method="init" destroy-method="destory"></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("关闭资源文件!");
}
}
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personservice = (PersonService)ctx.getBean("personService");
ctx.close();