Spring 框架作为一个管理 Bean 的 IoC 容器,那么 Bean 自然是 Spring 中的重要资源了,那 Bean 的作用域是什么意思?又有几种类型呢?接下来我们一起来看 。
PS:Java 中的公共类可称之为 Bean 或 Java Bean 。
1、作用域Bean 的作用域是指 Bean 在 Spring 整个框架中的某种行为模式 。
比如 singleton 单例作用域,就表示 Bean 在整个 Spring 中只有一份,它是全局共享的,当有人修改了这个值之后,那么另一个人读取到的就是被修改后的值 。
举个例子,比如我们在 Spring 中定义了一个单例的 Bean 对象 user(默认作用域为单例),具体实现代码如下:
@Componentpublic class UserBean {@Beanpublic User user() {User user = new User();user.setId(1);user.setName("Java"); // 此行为重点:用户名称为 Javareturn user;}}然后,在 A 类中使用并修改了 user 对象,具体实现代码如下:
@Controllerpublic class AController {@Autowiredprivate User user;public User getUser() {User user = user;user.setName("MySQL"); // 此行为重点:将 user 名称修改了return user;}}最后,在 B 类中也使用了 user 对象,具体实现代码如下:
@Controllerpublic class BController {@Autowiredprivate User user;public User getUser() {User user = user;return user;}}此时我们访问 B 对象中的 getUser 方法,就会发现此时的用户名为 A 类中修改的“MySQL”,而非原来的“Java”,这就说明 Bean 对象 user 默认就是单例的作用域 。如果有任何地方修改了这个单例对象,那么其他类再调用就会得到一个修改后的值 。
2、作用域分类在 Spring 中,Bean 的常见作用域有以下 5 种:
- singleton:单例作用域 。
- prototype:原型作用域(多例作用域) 。
- request:请求作用域 。
- session:会话作用域 。
- application:全局作用域 。
(1)singleton
- 官方说明:(Default) Scopes a single bean definition to a single object instance for each Spring IoC container 。
- 描述:该作用域下的 Bean 在 IoC 容器中只存在一个实例:获取 Bean(即通过 applicationContext.getBean等方法获取)及装配 Bean(即通过 @Autowired 注入)都是同一个对象 。
- 场景:通常 无状态 的 Bean 使用该作用域 。无状态表示 Bean 对象的属性状态不需要更新 。
- 备注: Spring 默认选择该作用域 。
- 官方说明:Scopes a single bean definition to any number of object instances 。
- 描述:每次对该作用域下的 Bean 的请求都会创建新的实例:获取 Bean(即通过 applicationContext.getBean 等方法获取)及装配 Bean(即通过 @Autowired 注入)都是新的对象实例 。
- 场景:通常 有状态 的 Bean 使用该作用域 。
- 官方说明:Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext 。
- 描述:每次 Http 请求会创建新的 Bean 实例,类似于 prototype 。
- 场景:一次 Http 的请求和响应的共享 Bean 。
- 备注:限定 Spring MVC 框架中使用 。
- 官方说明:Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext 。
- 火车王怎么没了 huochewang
- EJB开发
- 春节英文为啥不叫Chinese Spring Year?
- mung bean mrbeansg
- 网速在线测速 wangsuceshi
- 海外收款账户 境外收款
- 考试点考研网 kaoyanwang
特别声明:本站内容均来自网友提供或互联网,仅供参考,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
