Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Spring基础—— Bean 的作用域

一、在 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"/> @Testpublic 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@1ed718872.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.htmStruts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm基于 Spring 设计并实现 RESTful Web Services http://www.linuxidc.com/Linux/2013-10/91974.htmSpring-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.htmSpring 3.x 企业应用开发实战 PDF完整高清扫描版+源代码 http://www.linuxidc.com/Linux/2013-10/91357.htmSpring 的详细介绍:请点这里
Spring 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-07/133311.htm