博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaEE Bean的两种常用作用域 singleton(单例)和prototype(原型)
阅读量:3890 次
发布时间:2019-05-23

本文共 1527 字,大约阅读时间需要 5 分钟。

Spring4.3中为Bean的实例定义了其中作用域,这七种作用域中最常用的是singleton和prototype,今天就简单介绍这两个

作用域名称 说明
singleton(单例) 使用singleton定义的Bean在Spring容器中将只有一个实例,也就是说无论有多少个Bean在引用他,始终指向一个对象,这也是Spring容器默认的作用域,
prototype(原型) 每次通过Spring容器获取的prototype定义的Bean时,容器将创建一个新的Bean实例

一、singleton作用域

singleton是Spring默认的作用域,当Bean的作用域为singleton时,Spring容器就只会存在一个共享的Bean实例,并且所有对Bean的请求,只要id相同就会返回同一个Bean实例。singleton作用域对于无会话的Bean是最合适的选择。

1、在项目chapter02中创建一个com.itheima.scope包,在包中创建Scope类,该类不需要添加任何方法

package com.itheima.scope;public class Scope {}

2、然后创建一个配置文件beans4.xml,写入特定代码,如下面代码所示:

可以看到在xml中创建了两个bean且作用域均定义为singleton

3、在包中创建测试类,观察效果

package com.itheima.scope;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class ScopeTest4 {	private static ApplicationContext beanlizi;	public static void main(String[] args) {		String xmlPath = "com/itheima/scope/beans4.xml";		beanlizi = new ClassPathXmlApplicationContext(xmlPath);		System.out.println(beanlizi.getBean("scope1"));		System.out.println(beanlizi.getBean("scope1"));				System.out.println(beanlizi.getBean("scope2"));		System.out.println(beanlizi.getBean("scope2"));			}}

4、输出结果如下图所示:

一共四次发起Bean请求,输出了四次,但是只有两种不同的bean实例,这说明被定义作用于为singleton的bean如果请求id相同则会返回相同的bean实例

二、prototype作用域

对于需要保持会话的Bean(如:Struts2的Action类)应该使用prototype作用域。在使用prototype时,Spring容器会为每一个对Bean的请求都创建一个实例。

例如将上面例子中beans4.xml中两个bean的scope属性设置为prototype

再次运行测试类ScopeTest4,输出结果如下:

 

通过输出结果就会发现,四个bean实例各不相同,这就是bean的作用域的不同导致的

 

 

 

 

 

 

 

 

 

你可能感兴趣的文章
Windows 7 下登录界面里 Ctrl + Alt + Del 无法使用
查看>>
惠山赏菊 & 梅园赏桂
查看>>
[小技巧] cat /proc/modules 显示的地址为 0
查看>>
[游戏] chrome 的小彩蛋
查看>>
napi
查看>>
_GNU_SOURCE和__USE_GNU的差别
查看>>
Linux 有了 “DTrace”
查看>>
Linux 系统中僵尸进程
查看>>
一个 2 年 Android 开发者的 18 条忠告
查看>>
标志性文本编辑器 Vim 迎来其 25 周年纪念日
查看>>
[小技巧] chrome 的 vim 插件
查看>>
在 Linux 中查看你的时区
查看>>
[小技巧] [trac] Fix AttributeError: 'NullTranslations' object has no attribute 'add'
查看>>
[小技巧] Mac OS X上键盘的键位重映射
查看>>
Java对Oracle中Clob类型数据的读取和写入
查看>>
Spring中Quartz的配置
查看>>
MyBatis 防止 % _ sql 注入攻击 解决方法
查看>>
plsql oracle 无法解析指定的连接标识符
查看>>
Linux后台开发应该具备技能
查看>>
Eclipse Tomcat 无法添加项目
查看>>