Spring源码学习(1) Singleton 和 prototype

singleton作用域:当把一个Bean定义设置为singleton作用域是,Spring IoC容器中只会存在一个共享的Bean实例,并且所有对Bean的

请求,只要id与该Bean定义相匹配,则只会返回该Bean的同一实例。值得强调的是singleton作用域是Spring中的缺省作用域。
prototype作用域:prototype作用域的Bean会导致在每次对该Bean请求(将其注入到另一个Bean中,或者以程序的方式调用容器的getBean

()方法)时都会创建一个新的Bean实例。根据经验,对有状态的Bean应使用prototype作用域,而对无状态的Bean则应该使用singleton作用

域。
对于具有prototype作用域的Bean,有一点很重要,即Spring不能对该Bean的整个生命周期负责。具有prototype作用域的Bean创建后交由调

用者负责销毁对象回收资源。
简单的说:
singleton 只有一个实例,也即是单例模式。
prototype访问一次创建一个实例,相当于new。 
应用场合:
1.需要回收重要资源(数据搜索库连接等)的事宜配置为singleton,如果配置为prototype需要应用确保资源正常回收。
2.有状态的Bean配置成singleton会引发未知问题,可以考虑配置为prototype
 

singleton指的是,仅仅只有一个共享的实例被管理,所有的请求对于该beans的,都只能返回一个实例。该实例被存在单例bean的缓存里。该单例和设计模式中的单例是有区别的,准确的说是spring的singleton指的是一个容器一个实例。

prototype指的是每次请求都有一个新的实例。每次请求都需要通过getBean()方法来调用通过容器。一条规则为,singleton作为无状态的bean使用,prototype作为有状态的bean使用。下面的例子介绍了区别:

<?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-3.0.xsd"> <bean id="weatherDAO" class="com.StaticDataWeatherDAOImpl"></bean> <bean id="weatherService" class="com.WeatherServiceImpl"> <constructor-arg name="weatherDAO"> <ref local="weatherDAO"/> </constructor-arg> </bean> <bean id="personBean" class="com.PersonBean" scope="singleton"> </bean> </beans>

package com;

import java.util.GregorianCalendar;

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

public class WeatherServiceTest {

@Test public void TestSample2(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("com/applicationContext.xml"); WeatherService ws = (WeatherService) ctx.getBean("weatherService"); Double high = ws.getHistoricalHigh(new GregorianCalendar(2004,0,1).getTime()); PersonBean pb = (PersonBean)ctx.getBean("personBean"); System.out.println(pb.getName()); pb.setName("lili"); System.out.println(pb.getName()); PersonBean pb1 = (PersonBean)ctx.getBean("personBean"); System.out.println(pb1.getName()); // pb.setName("lili"); // System.out.println(pb1.getName()); } }

运行结果为:

null lili lili

如果改为prototype

运行结果为

null lili null

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值