Spring Bean作用域实例

在Spring中,bean作用域用于确定哪种类型的 bean 实例应该从Spring容器中返回给调用者。bean支持的4种范围域:

作用域 描述
单例(singleton) (默认)每一个Spring IoC容器都拥有唯一的一个实例对象
原型(prototype) 一个Bean定义,任意多个对象
请求(request) 一个HTTP请求会产生一个Bean对象,也就是说,每一个HTTP请求都有自己的Bean实例。只在基于web的Spring ApplicationContext中可用
会话(session) 限定一个Bean的作用域为HTTPsession的生命周期。同样,只有基于web的Spring ApplicationContext才能使用
注:意味着只有在一个基于web的Spring ApplicationContext情形下有效!在大多数情况下,可能只处理了 Spring 的核心作用域 - 单例和原型,默认作用域是单例。

单例VS原型
这里有一个例子来说明,bean的作用域单例和原型之间的不同:

File:CustomerService.java

public class CustomerService {

	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
}

1.单例例子
如果 bean 配置文件中没有指定 bean 的范围,默认为单例。

File:beans.xml




	

执行结果:

public class Test {

	public static void main(String[] args) {
		
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		CustomerService custA =  (CustomerService) ctx.getBean("customerService");
		custA.setMessage("Message by custA");
    	System.out.println("Message : " + custA.getMessage());
    	
    	//retrieve it again
    	CustomerService custB = (CustomerService)ctx.getBean("customerService");
    	System.out.println("Message : " + custB.getMessage());
	}
}

输出结果:

二月 22, 2018 12:11:57 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3fa77460: startup date [Thu Feb 22 12:11:57 CST 2018]; root of context hierarchy
二月 22, 2018 12:11:57 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans1.xml]
Message : Message by custA
Message : Message by custA

由于 bean 的 “CustomerService' 是单例作用域,第二个通过提取”custB“将显示消息由 ”custA' 设置,即使它是由一个新的 getBean()方法来提取。在单例中,每个Spring IoC容器只有一个实例,无论多少次调用 getBean()方法获取它,它总是返回同一个实例。

2.原型例子
如果想有一个新的 “CustomerService”bean 实例,每次调用它的时候,需要使用原型(prototype)来代替。




	

运行-执行:

二月 22, 2018 12:16:35 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3fa77460: startup date [Thu Feb 22 12:16:35 CST 2018]; root of context hierarchy
二月 22, 2018 12:16:35 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans1.xml]
Message : Message by custA
Message : null

你可能感兴趣的:(Spring)