论坛首页 Java企业应用论坛

Spring中bean的作用域(scope),sington与prototype

浏览 4531 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (2) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-04-06  

在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那么打印的就将是对象不相等了

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics