第五章第五节-bean的范围

本文深入探讨了Spring框架中Bean的四种作用域:singleton、prototype、request和session,重点讲解了prototype作用域如何确保每次获取Bean时都是新的实例。通过代码示例,展示了不同作用域下Bean实例的创建和引用行为。

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

一、bean的范围        

       与HelloWorld项目一样创建一个普通的java项目,创建一个bean类Person,MainTest测试类,spring.xml配置文件(后面有完整的代码)。

       先来看MainTest的代码,主要部分是通过getBean两次获取Person的实例,然后打印两个引用的“==”结果。

       再来看配置文件,当还没有scope=“prototype”的时候打印结果为true,即两个引用指向的是一个对象;当使用了prototype时,打印结果为false。表示是不同的两个对象,这就是scope的prototype取值的作用每次都返回一个新的实例。

       关于scope的取值见下表。我们这里只讨论了prototype这一个属性。sigleton属性在项目中也可以测试,其他两个则需要在web项目中才可测试。

 

属性值

作用

sigleton

在springIOC容器中仅存一个实例,Bean以单例存在。

prototype

每次通过容器的方法获取bean时都返回一个新实例。

request

http每次请求都创建一个Bean,作用于WebApplicationContext域

session

同一个合同http的session共享一个Bean实例,作用于WebApplicationContext域

 

 

 

import com.escore.beans.Person;

public class MainTest {
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
		
		Person person1 = ctx.getBean(Person.class);
		Person person2 = ctx.getBean(Person.class);
		
		System.out.println(person1==person2);
		
		ctx.close();
	}

}
<bean id="person" class="com.escore.beans.Person"
		scope="prototype">
		<property name="name" value="scopeTest"></property>
	</bean>

------------------------------------整个小案例的完整代码---------------------------
Person.java

 

 

public class Person {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + "]";
	}

}

MainTest.java

 

 

import com.escore.beans.Person;

public class MainTest {
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
		
		Person person1 = ctx.getBean(Person.class);
		Person person2 = ctx.getBean(Person.class);
		
		System.out.println(person1==person2);
		
		ctx.close();
	}

}

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- scope设置bean的作用范围 -->
	<bean id="person" class="com.escore.beans.Person"
		scope="prototype">
		<property name="name" value="scopeTest"></property>
	</bean>

</beans>

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值