Spring bean的作用域

本文介绍了Spring框架中Bean的七种作用域:singleton、prototype、request、session、globalSession、application以及websocket,并解释了如何通过配置来选择不同的作用域。

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

7.5 Bean scopes
When you create a bean definition, you create a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that,as with a class, you can create many object instances from a single recipe.
You can control not only the various dependencies and configuration values that are to be plugged into
an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition. This approach is powerful and flexible in that you can choose the scope of the objects you create through configuration instead of having to bake in the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes: out of the
box, the Spring Framework supports seven scopes, five of which are available only if you use a webaware ApplicationContext.
The following scopes are supported out of the box. You can also create a custom scope.

这里写图片描述

Bean的作用域分7种:
singleton:单例(在每一个Spring容器中只实例化一个对象)
prototype:一个bean可以生成任意数量的对象实例
request:在每一次Http请求后都会产生一个bean实例
session:在每一个session中实例化一次
globalSession:在全局session中实例化
application:在一个应用程序内实例化
websocket:在websocket里实例化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值