ITeye博客

Spring中bean的作用域

tianhei · 2011-03-17 16:32 · Spring · 企业架构 · ActiveMQ · Spring · prototype · JMS · Bean · Markdown

Spring中bean的作用域

 

Spring中bean的作用域用scope来表示。

scope的值有两个:

singleton为单粒,即Spring IoC容器只会创建该bean的唯一一个实例,这也是默认的。该实例就会一直放在缓存里供大家使用。

prototype为原型,即每一次请求都会产生一个新的bean实例。

 

以实例说明

 

Bean

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 version="1.0" encoding="UTF-8"?>

<beans xmlns="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">

    <bean name="bean1" class="com.cos.bean110317.Bean1" scope="singleton">
    <!-- bean name="bean1" class="com.cos.bean110317.Bean1" scope="prototype" -->
        <property name="name" value="zhangsan"/>
    </bean>
</beans>

当scope不写的时候默认为singleton

当scope为singleton的时候,输出结果bean11 == bean12

当scope为prototype的时候,输出结果bean11 != bean12 

 

测试类

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");
        }
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。