bean的作用范围以及bean的生命周期

bean的作用范围取值有五种(scope属性控制):

singleton:单例,也是默认值

prototype:  多例,比如让Spring接管struts2的action的时候就必须配置此属性

request:  一次请求以及此次请求的转发

session: 作用范围是一次会话

globalsession:  作用范围是一次全局绘画,比如多台服务器之间需要共用同一个bean的时候就需要此属性。

bean的生命周期(现只讨论ApplicationContext下的情况):

singleton状态下的bean,生命周期:

创建:容器创建时bean创建

存在:容器存在时bean一直存在

销亡:容器消亡bean随之销亡

我们用bean标签中的init-method、destory-method看看效果:

这是相关类:

public class CustomerServiceImpl implements ICustomerService {
	
	public CustomerServiceImpl() {
		System.out.println("serviceImpl创建了");
	}
	
	public void init() {
		System.out.println("初始化方法调用了");
	}
	
	public void destory() {
		System.out.println("销毁方法调用了");
	}
	@Override
	public void saveCustomer(Object obj) {
		// TODO Auto-generated method stub
		
	}

}

 这是bean的配置:

<bean id="customerService" class="com.dimples.service.impl.CustomerServiceImpl" init-method="init" destroy-method="destory"></bean>

测试:

public static void main(String[] args) {
		ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		System.out.println(ac.getBean("customerService"));
		ac.close();

	}

这是结果:

log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
serviceImpl创建了
初始化方法调用了
com.dimples.service.impl.CustomerServiceImpl@5700d6b1
销毁方法调用了

然后是多例模式----prototype,它的生命周期:

创建:使用时(这里的使用和以往意义上的使用不太一样,这里的使用就是值构造方法被调用了)

存在:只要在使用中就一直存在

销毁:不再被引用了

这是bean.xml中的配置:

<bean id="customerService" class="com.dimples.service.impl.CustomerServiceImpl" scope="prototype" init-method="init" destroy-method="destory"></bean>

运行效果:

log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
serviceImpl创建了
初始化方法调用了
com.dimples.service.impl.CustomerServiceImpl@6500df86

最后梳理一下ApplicationContext、BeanFactory两种容器和bean的三种创建以及bean的五种scope之间的关系:

ApplicationContext和BeanFactory控制的是创建容器的时候要不要同时创建bean;而bean的三种配置方式控制的是通过哪种方式来创建bean,比如是直接反射创建还是静态工厂还是实例工厂;而bean的五种scope控制的是创建bean以后它的作用范围(或者说是它的存活期间)。其中单例的bean在容器期间一直存活,多例模式的bean在创建它的那个线程中若在被引用则存活,长时间不引用会被Java垃圾回收器回收。

猜你喜欢

转载自blog.csdn.net/dimples_qian/article/details/81275496