您的位置:首页 > 编程语言 > Java开发

Spring源码学习(1) Singleton 和 prototype

2014-04-15 23:34 204 查看
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/beanshttp://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 {@Testpublic 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());}}运行结果为:nulllililili如果改为prototype运行结果为nulllilinull
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring 源码 singleton