Spring Bean的两种常用作用域
- Spring Bean的两种常用作用域
Spring Bean实例的作用域字段scope有两种常用的作用域singleton和prototype两种
- singleton是Spring容器的默认作用域,当bean的作用域为singleton时,spring容器就只会存一个共享的bean实例,所以有关于Bean的请求,只要与bean的属性id相配,就会返回同一个Bean实例
- prototype对需要保持会话状态的Bean应用,应使用prototype作用域,在使用prototype时spring会为每个对该bean的请求创建一个新的实例
- 测试小demo
1)创建一个类
public class Scope { } |
2)创建该类的bean实例的配置文件applicationContext.xmml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"> <!-- 将指定类配置给spring,让spring创建其对象的实例 --> <bean id="scope" class="org.lyl.scope.Scope"scope="singleton "></bean> </beans> |
3)测试bean的作用域
public class ScopeTest { public static void main(String[] args) { //初始化spring容器,加载配置文件 ApplicationContext aw=new ClassPathXmlApplicationContext("applicationContext.xml");
//输出获得的实例 System.out.println(aw.getBean("scope")); System.out.println(aw.getBean("scope")); } } |
输出结果如图
结果显示当bean的作用域为singleton时,spring容器就只会存一个共享的bean实例,两次有关于bean的请求,返回同一个地址
将bean的作用域改为prototype时
<bean id="scope" class="org.lyl.scope.Scope"scope="prototype"></bean> |
输出结果如图
结果显示在使用prototype时spring会为每个对该bean的请求创建一个新的实例,两次有关于bean的请求,指向不同的个地址