---
title: "spring中bean的作用域"
author: "fojian"
date: "2009-11-15T19:07:03Z"
tags: ["Bean", "IOC", "Spring", "XML", "prototype"]
slug: "spring-bean"
draft: false
lastmod: "2009-11-15T19:26:01Z"
id: 517661
url: "https://fojian.iteye.com/blog/517661"
---

signleton:在每个Spring IoC容器中定义一个Bean只有一个实例。默认情况下会在容器启动时初始化Bean，如果要在第一次获取Bean的时候才初始化Bean，可在xml文件中指定Bean节点的lazy-init="true"来延迟初始化Bean。如：  
&lt;bean id="xxx" class="xx.xx.xxBean" lazy-init="true"&gt;  
如果要对所有的Bean都应用延迟初始化，可在根节点beans设置default-lazy-init="true",如：  
&lt;beans id="xxx" class="xx.xx.xxBean" default-lazy-init="true"&gt;

prototype:每次从容器中获取的Bean都是新的对象。默认情况下会在调用Bean的时初始化Bean。

 

在Spring的配置中，对于无状态的Bean可将其配置成singleton，对于有状态的配置成protoType，如Struts1.x的Action是单例的,因为Action是无状态的，不需对Action内的状态进行保存，但在Struts2中，Action是有状态的，其中可能注入了一些Bean作为属性，这时在Spring配置中用了Bean的scope范围的默认值singleton时，Action内的成员变量是线程不安全的，这样在用到Action时成员变量就会被多次使用，从而造成一些状态上的错误，解决的方法是在Spring的配置文件中将Bean的scope属性值设为prototypt，这样就使得在请求Action的时候每次都会生成一个Action的实例，一般建议的Spring的ActionBean中将scope设为prototypt。