---
title: "spring中的Bean"
author: "拳拳天下"
date: "2015-02-06T16:17:45Z"
tags: []
categories: ["互联网"]
slug: "spring-bean"
draft: false
lastmod: "2015-02-06T16:17:45Z"
id: 2184134
url: "https://smiling8866.iteye.com/blog/2184134"
---

当通过Spring容器创建Bean实例时，不仅可以完成Bean的实例化，还可以为该Bean指定作用域。Spring中的Bean有5中作用域。

        1.singleton:单例模式，在整个Spring Ioc中，使用singleton定义的Bean将只有一个实例。

        2.prototype:原型模式，每次通过容器的getBean方法获取prototype定义的Bean时，都将产生一个新的

           Bean实例。

        3.request:对每次Http请求。只有在web中使用spring时才有效。

        4.session：对每次Http session。只有在web中使用spring时才有效。

        5.global session:

        对于singleton作用域的Bean，每次请求该id的Bean，都将返回同一个共享实例，因而两次获取的Bean实例完全相同；但是对于prototype作用域的Bean，每次请求该id的Bean都将产生新的实例，因此两次请求获得的Bean实例不相同。

        对于使用request、session、global session范围的Bean时，还需要在web.xml中配置一些参数。可以采用listener配置，也可以采用Filter配置。因为如果使用了支持Servlet2.4以前规范的web容器，这样的容器是不支持listener规范的。

      

 

          当两个Bean之间有依赖关系时，配置这两个bean时称为配置合作者Bean，除使用ref进行配置外，还可以使用自动装配注入合作者Bean。

 

使用自动装配注入合作者Bean:

       spring的自动装配可以通过&lt;beans....../&gt;元素的default-autowire属性指定，也可通过&lt;bean..../&gt;元素的autowire属性指定。自动装配可以指定到单独的Bean，也就是说，同一个Spring容器中完全可让某些Bean使用自动装配，而另一些Bean不适用自动装配。

autoware属性可以接受如下值：

n0:

byName:

byType:

constructor:

autodelect: