Spring容器对Bean组件的管理

一.Bean对象创建时机:默认是随容器创建,通过lazy-init可以改变对象实例化时机
(a)默认lazy-init=default||false:
当spring容器实例化的时候,并把
容器中对象全部完成实例化

<bean id="bean" class="com.tarena.entity.Bean" lazy-init="false"/>

(b)lazy-init="true"
当从spring容器中获取对象时候在对对象
实例始化

(c)设置全局default-lazy-init="true"
整个配置文件中对象都实例化延迟
<beans ...
default-lazy-init="true">
</beans>
注意:在使用定时器的时候,不能使用lazy-init="true"

二.Bean对象的创建模式

1.singleton:spring容器对象默认是单例模式每次只成一个实例。

<bean id="" class="" scope="singleton"/> struts1:

2.prototype:多例,spring容器会每次都为对象产生一个新实例。

<bean id="" class="" scope="prototype"/> struts2:

scope:在web开发中使用request,session.

回顾:

会话:与服务器端多次请求和响应过程
pageContext:当前页面
session:一次会话
request:一次请求
application:整个应用服务器

测试类:

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 id="bean" class="com.tarena.entity.Bean"/>

运行结果:

我出生了
单例

当配置文件中<bean id="bean" class="com.tarena.entity.Bean" scope="prototype"/>

运行结果:

我出生了
我出生了
多例

三.Bean对象初始化和销毁

(a)在spring配置文件定义销毁方法和初始化方法
<bean init-method="init" destroy-method="destroy">
(b)在Bean 对象中定义销毁方法和初始化方法
public void init(){}
public void destroy(){}
(c)spring容器自动调用销毁方法和初始化方法

注意:销毁方法在spring容器销毁才去调用
AbstractApplicationContext提供销毁容器方法
close();//销毁容器

Bean对象时多例不支持destroy(){}销毁
scope="prototype"


测试类:

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();

	}
}

当配置文件中<bean id="bean" class="com.tarena.entity.Bean" init-method="init" destroy-method="destroy" />
运行结果:

我出生了
执行init方法
我是一个豆子
执行destroy

当配置文件中<bean id="bean" class="com.tarena.entity.Bean" init-method="init" destroy-method="destroy" scope="prototype"/>

运行结果:
我出生了
执行init方法
我是一个豆子

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值