---
title: "Spring中bean的作用域(scope),sington与prototype"
author: "ideaforj"
date: "2009-04-06T15:12:39Z"
tags: []
categories: ["企业架构"]
slug: "spring-bean-scope-sington-prototype"
draft: false
lastmod: "2009-04-06T15:12:39Z"
id: 362252
url: "https://ideaforj.iteye.com/blog/362252"
---

在spring2.0之前bean只有2种作用域即：singleton(单例)、prototype，Spring2.0以后，增加了session、request、global session三种专用于Web应用程序上下文的Bean，下面就让我们来看看singleton与prototype在spring的作用域（scope）中到底有什么区别

```
package spring.scope;

public class Person {

	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
```

 定义一个普通的Person类

 

```
<?xml version="1.0" encoding="UTF-8"?>

<!--
  - Application context definition for JPetStore's business layer.
  - Contains bean references to the transaction manager and to the DAOs in
  - dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").
  -->
<beans xmlns="http://www.springframework.org/schema/beans"
	     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	     xmlns:aop="http://www.springframework.org/schema/aop"
	     xmlns:tx="http://www.springframework.org/schema/tx"
	     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

<!-- singleton prototype ||||session   request   global session 三种专用于Web应用程序上下文的Bean
		<bean id="bean1" class="spring.scope.Person" scope="prototype"/>
 -->
 		<bean id="bean1" class="spring.scope.Person" scope="singleton"></bean>
		
		
</beans>
```

 编写配置文件，首先将spring的scope定义为singleton类型

```
package spring.scope;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import junit.framework.TestCase;

public class ScopeTest extends TestCase {

	private BeanFactory beanFactory;
	
	@Override
	protected void setUp() throws Exception {
		beanFactory = new ClassPathXmlApplicationContext("applicationContext.xml");
	}
	
	public void testScope1() {
		Person p1= (Person)beanFactory.getBean("bean1");
		Person p2= (Person)beanFactory.getBean("bean1");
		if(p1 == p2) {
			System.out.println("对象相等");
		} else {
			System.out.println("对象不相等");
		}
	}
}
```

 由于上面配置的是singleton，当然打印的是对象相等，如果配置的是prototype那么打印的就将是对象不相等了