(a)默认lazy-init=default||false:
当spring容器实例化的时候,并把
容器中对象全部完成实例化
(b)lazy-init="true"
当从spring容器中获取对象时候在对对象
实例始化
(c)设置全局default-lazy-init="true"
整个配置文件中对象都实例化延迟
default-lazy-init="true">
注意:在使用定时器的时候,不能使用lazy-init="true"
二.Bean对象的创建模式
1.singleton:spring容器对象默认是单例模式每次只成一个实例。
2. prototype:多例,spring容器会每次都为对象产生一个新实例。
scope:在web开发中使用request,session.
回顾:
会话:与服务器端多次请求和响应过程
pageContext:当前页面
session:一次会话
request:一次请求
application:整个应用服务器
测试类:
[java]
public class Bean {
public void show(){
System.out.println("我是一个豆子");
}
public Bean() {
System.out.println("我出生了");
}
public static void main(String[] args) {
ApplicationContext ac = new
FileSystemXmlApplicationContext("classpath:applicationContext.xml");
Bean bean1 = (Bean)ac.getBean("bean");
Bean bean2 = (Bean)ac.getBean("bean");
if(bean1 == bean2){
System.out.println("单例");
}else{
System.out.println("多例");
}
}
}
当配置文件中
运行结果:
我出生了
单例
当配置文件中
运行结果:
我出生了
我出生了
多例
三.Bean对象初始化和销毁
(a)在spring配置文件定义销毁方法和初始化方法
(b)在Bean 对象中定义销毁方法和初始化方法
public void init(){}
public void destroy(){}
(c)spring容器自动调用销毁方法和初始化方法
注意:销毁方法在spring容器销毁才去调用
AbstractApplicationContext提供销毁容器方法
close();//销毁容器
Bean对象时多例不支持destroy(){}销毁
scope="prototype"
测试类:
[java]
public class Bean {
public void show(){
System.out.println("我是一个豆子");
}
public Bean() {
System.out.println("我出生了");
}
//定义初始化方法
public void init(){
System.out.println("执行init方法");
}
public void destroy(){
System.out.println("执行destroy");
}
public static void main(String[] args) {
AbstractApplicationContext ac = new
FileSystemXmlApplicationContext("classpath:applicationContext.xml");
Bean bean = (Bean)ac.getBean("bean");
bean.show();
ac.close();
}
} www.2cto.com
当配置文件中
运行结果:
我出生了
执行init方法
我是一个豆子
执行destroy
当配置文件中
运行结果:
我出生了
执行init方法
我是一个豆子