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

本文深入探讨了Spring框架中两种核心作用域:singleton与prototype的区别。通过实例演示了这两种作用域如何影响Bean实例的创建和生命周期,并提供了源代码及配置文件进行说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值