Bean-Scopes作用域
- Singleton 单例
- Prototype 原型
- request 请求
- session 会话
- application 应用
- WebSocket 连接
主要使用前两种
Singleton 单例模式
单例模式是Spring的默认机制
只管理Singleton bean 的一个共享实例,带有一个或多个match bean定义的id到导致只返回一个特定的bean实例
定义的bean限定为singleton时,只创建该bean定义的object的一个实例,存储在singleton缓存中,后续的请求都引用缓存中的实例
只创建一个实例
这个共享实例被共享到每个协作对象中
Spring中的singleton bean概念于singleton pettern的概念不同,如果在单个 Spring 容器中为特定 class 定义一个 bean,则 Spring 容器将创建该_ bean 定义所定义的 class 的一个且仅一个实例。
<bean id="accountService" class="com.something.DefaultAccountService"/>
<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>
Demo
-
<bean id="studentTest" class="com.haoyun.POJO.Student" > <property name="address" ref="address"/> </bean> <bean id="studentTest2" class="com.haoyun.POJO.Student" > <property name="address" ref="address"/> </bean> <bean id="address" class="com.haoyun.POJO.Address" p:address="address" scope="singleton" />
-
address是单例模式的,根据单例模式的性质,应该值会创建一个实例,那只创建一个实例,那些被创建的实例中的address成员使用的应该是同一个引用
-
@Test public void BeanTest(){ ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); Student studentTest = (Student) classPathXmlApplicationContext.getBean("studentTest"); Student studentTest2 = (Student) classPathXmlApplicationContext.getBean("studentTest2"); System.out.println(studentTest); System.out.println(studentTest2); System.out.println(studentTest == studentTest2); System.out.println(studentTest.getAddress() == studentTest2.getAddress()); }
-
-
得出的结果是两个对象是不同的,但是address是同一个对象,使用同一个reference
ProtoType 原型模式
bean部署的不是单例模式的原型范围都会创建一个新的bean实例,并对该特定bean发出请求,
每个bean都是一个单独的对象
配置和组装object交给client,client code必须清理prototype-scoped object释放原型beans所拥有的昂贵资源,之后可以尝试自定义bean post-processor,释放资源
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
每次从容器中get的时候都会产生一个新的对象
其余的request,session,application,这些只能在web开发中使用到,自行理解