Spring中bean的作用域

创新互联建站是一家专注于成都网站设计、成都网站建设与策划设计,黄南州网站建设哪家好?创新互联建站做网站,专注于网站建设十多年,网设计领域的专业建站公司;建站业务涵盖:黄南州等地区。黄南州做网站价格咨询:18982081108
Spring中bean的作用域用scope来表示。
scope的值有两个:
singleton为单粒,即Spring IoC容器只会创建该bean的***一个实例,这也是默认的。该实例就会一直放在缓存里供大家使用。
prototype为原型,即每一次请求都会产生一个新的bean实例。
以实例说明
Bean
Java代码
- package com.cos.bean110317;
 - public class Bean1 {
 - private String name;
 - public String getName() {
 - return name;
 - }
 - public void setName(String name) {
 - this.name = name;
 - }
 - }
 
applicationContext_5.xml
Xml代码
- "1.0" encoding="UTF-8"?>
 - "http://www.springframework.org/schema/beans"
 - xmlns:amq="http://activemq.apache.org/schema/core" xmlns:jms="http://www.springframework.org/schema/jms"
 - xmlns:context="http://www.springframework.org/schema/context"
 - 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
 - http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.4.0.xsd
 - http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
 - http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd">
 - "bean1" class="com.cos.bean110317.Bean1" scope="singleton">
 - "name" value="zhangsan"/>
 
当scope不写的时候默认为singleton
当scope为singleton的时候,输出结果bean11 == bean12
当scope为prototype的时候,输出结果bean11 != bean12
测试类
Java代码
- package com.cos.bean110317;
 - import org.springframework.beans.factory.BeanFactory;
 - import org.springframework.context.support.ClassPathXmlApplicationContext;
 - public class Test {
 - public static void main(String[] args) {
 - BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext_5.xml");
 - Bean1 bean11 = (Bean1) factory.getBean("bean1");
 - Bean1 bean12 = (Bean1) factory.getBean("bean1");
 - if(bean11 == bean12){
 - System.out.println("bean11 == bean12");
 - }else{
 - System.out.println("bean11 != bean12");
 - }
 - }
 - }
 
【编辑推荐】
Struts VS Spring两种MVC框架比较
Spring MVC框架的高级配置
Spring MVC框架的高级配置(上)
Spring MVC框架的高级配置(下)
设计REST风格的Java MVC框架:WebWind
                名称栏目:详解Spring中bean的作用域
                
                网站URL:http://www.csdahua.cn/qtweb/news36/78386.html
            
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网