你好,游客 登录 注册 搜索
背景:
阅读新闻

Spring基础—— Bean 的作用域

[日期:2016-07-19] 来源:Linux社区  作者:solverpeng [字体: ]

一、在 Spring Config 文件中,在 <bean> 元素的 scope 属性里设置 Bean 的作用域。默认为 singleton ,单例的。

二、在不引入 spring-web-4.0.0.RELEASE.jar 包的情况下,scope 属性只有两个值:singleton 和 prototype

1.singleton(单例)

Spring 为每个在 IOC 容器中声明的 Bean 创建一个实例,整个 IOC 容器范围都能共用。通过 getBean() 返回的对象为同一个对象。

如:

<bean class="com.linuxidc.spring.bean.Employee" id="employee" p:empName="emp01" p:age="12"/>
 
@Test
public void test01() {
  Employee employee = ctx.getBean(Employee.class);
  System.out.println(employee);

  Employee employee2 = ctx.getBean(Employee.class);
  System.out.println(employee2);
}

控制台输出:

com.linuxidc.spring.bean.Employee@1ed71887
com.linuxidc.spring.bean.Employee@1ed71887

2.prototype(原型),每次调用 getBean() 都会返回一个新的实例

<bean class="com.linuxidc.spring.bean.Employee" id="employee" p:empName="emp01" p:age="12" scope="prototype"/>
 
@Test
 public void test01() {
  Employee employee = ctx.getBean(Employee.class);
  System.out.println(employee);

  Employee employee2 = ctx.getBean(Employee.class);
  System.out.println(employee2);
}

控制台输出:

com.linuxidc.spring.bean.Employee@652e3c04
com.linuxidc.spring.bean.Employee@3e665e81

这里不对 web 环境的 Bean 的作用域进行讨论,事实上,我们常用到的也就这两种。

Spring中如何配置Hibernate事务 http://www.linuxidc.com/Linux/2013-12/93681.htm

Struts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm

基于 Spring 设计并实现 RESTful Web Services http://www.linuxidc.com/Linux/2013-10/91974.htm

Spring-3.2.4 + Quartz-2.2.0集成实例 http://www.linuxidc.com/Linux/2013-10/91524.htm

使用 Spring 进行单元测试 http://www.linuxidc.com/Linux/2013-09/89913.htm

运用Spring注解实现Netty服务器端UDP应用程序 http://www.linuxidc.com/Linux/2013-09/89780.htm

Spring 3.x 企业应用开发实战 PDF完整高清扫描版+源代码 http://www.linuxidc.com/Linux/2013-10/91357.htm

Spring 的详细介绍请点这里
Spring 的下载地址请点这里

本文永久更新链接地址http://www.linuxidc.com/Linux/2016-07/133311.htm

linux
相关资讯       Spring基础  Spring Bean作用域  Bean作用域 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款