spring——singleton和prototype作用域

IOC容器对Bean的管理有5种作用域:Singleton、Prototype、request、session、globalSession

Singleton作用域代表在IOC容器中只有一个Bean的实现,一个实例

Protorype作用域代表当使用getBean()方法取得一个Bean时,IOC容器新建一个指定Bean实例,多实例

applicationContext中scope为prototype,当每次执行getBean()时IOC容器都会新建一个类实例,所以在控制台输出的时间都不同

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<bean id="get_date" class="java.util.Date" scope="prototype"/>
</beans>

getdate

package com.test;

import java.util.Date;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class GetDate {

	public static void main(String[] args){
		//获取应用程序上下文接口
		ApplicationContext apl = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		try {
			//反复调用getBean来查看时间
			Date date = (Date) apl.getBean("get_date");
			//休息3秒
			Thread.sleep(3000);
			System.out.println(date);
			
			date = (Date) apl.getBean("get_date");
			Thread.sleep(3000);
			System.out.println(date);
			
			date = (Date) apl.getBean("get_date");
			Thread.sleep(3000);
			System.out.println(date);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
}

aplicationContext中scope改为singleton时,因为它是一个单实例,所以它取到的Bean永远都是一个,在控制台输出的时间相同

<bean id="get_date" class="java.util.Date" scope="singleton"/>

 

猜你喜欢

转载自blog.csdn.net/Milan__Kundera/article/details/82084150