Spring 当中的Bean 作用域

news2024/9/21 0:42:18

Spring 当中的Bean 作用域

文章目录

  • Spring 当中的Bean 作用域
  • 每博一文案
  • 1. Spring6 当中的 Bean的作用域
    • 1.2 singleton 默认
    • 1.3 prototype
    • 1.4 Spring 中的 bean 标签当中scope= 属性其他的值说明
    • 1.5 自定义作用域,一个线程一个 Bean
  • 2. 总结:
  • 3. 最后:


每博一文案

青年,青年!无论受怎样的挫折和打击,都要咬着牙关挺住,因为你们完全有机会重建生活;只要不灰心丧气,每一次挫折就只不过是通往新境界的一块普通绊脚石,而绝不会置人于死命
									_____路遥《平凡的世界》
飞机上邻座的姐姐
独自一人坐飞机去见异地的男友
异地恋赤诚的人好像越来越少
我不自觉地问她
如果以后分手了不会觉得可惜么
她一边低头和男友报备自己落座了
一边回答说“我不是确认了不会分手才去爱他的,我恰恰是因为确定了我们有可能会分手才更要
用力去爱他的,更何况,人是用来拥有的,不是吗”
								———————《网友评论》

1. Spring6 当中的 Bean的作用域

1.2 singleton 默认

默认情况下,Spring的IoC容器创建的Bean对象是单例的。

我们来检验一下:

首先,方便大家处理,下面明确出对应相关的 maven配置信息pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.rainbowsea</groupId>
    <artifactId>spring6-007-circular-dependency</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.11</version>
        </dependency>


        <!-- junit4 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

对应配置的 bean 的类是 User 这个类 ,为了方便辨析,简单明了,这个 类,就不设置属性了。就是一个空空的类。

package com.rainbowsea.spirngBean;

public class User {
    public User() {
        System.out.println("User() 的无参数构成方法");
    }
}

配置 Spring框架当中的xml 配置文件,让 Spring 知道我们的 User 这个类,并进行管理

在这里插入图片描述

<?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">

    <bean name="user" class="com.rainbowsea.spirngBean.User"></bean>
</beans>

下面编写测试:代码,进行一个测试,验证,Spring 默认是否是 单例的 。这里我们启动多线程,进行一个测试

在这里插入图片描述

package com.ranbowsea.test;

import com.rainbowsea.spirngBean.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testScope {

    @Test
    public void test01() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
        User user = applicationContext.getBean("user", User.class);
        User user1 = applicationContext.getBean("user", User.class);
        System.out.println(user);
        System.out.println(user1);

        // 启动线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                User user2 = applicationContext.getBean("user", User.class);
                User user3 = applicationContext.getBean("user", User.class);
                System.out.println(user2);
                System.out.println(user3);
            }
        }).start();
    }
}

在这里插入图片描述

从结果上看:

  1. 无参构造方法仅仅只被调用了一次
  2. 四个user对象,的地址是一样的

说明:无论是执行多少次,applicationContext.getBean ,还是启动多个线程,都是同一个User对象. 是单例的

这个对象在什么时候创建的呢?可以为SpringBean提供一个无参数构造方法,测试一下,如下:

在这里插入图片描述

从结果上来看:是在 new ClassPathXmlApplicationContext() 的时候就已经,执行了构造方法(Bean对象的创建是在初始化Spring上下文的时候就完成的。)

其中: singletonSpring框架 默认的,也是单例的。

我们可以使用:可以在bean标签中指定 scope属性的值为 singleton 。我们测试如下。

在这里插入图片描述

<?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">

    <bean name="user" class="com.rainbowsea.spirngBean.User" scope="singleton"></bean>
</beans>

在这里插入图片描述

通过测试得知,没有指定scope属性时,默认是singleton单例的。

1.3 prototype

如果想让Spring的Bean对象以**多例** 的形式存在,可以在bean标签中指定 scope属性的值为:prototype,这样Spring会在每一次执行getBean()方法的时候创建Bean对象,调用几次则创建几次。

在这里插入图片描述

在这里插入图片描述

<?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">

    <bean name="user" class="com.rainbowsea.spirngBean.User" scope="prototype"></bean>
</beans>

我们来是:用 User 这个类进行测试,使用:

在这里插入图片描述

在这里插入图片描述


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testScope {
    @Test
    public void test() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
        User user = applicationContext.getBean("user", User.class);
        User user1 = applicationContext.getBean("user", User.class);
        System.out.println(user);
        System.out.println(user1);

    }
}

从结果上看:

1.调用了两次无参数构成方法()

2.是两个不同的 user对象的地址

启动多个线程,也是会存在多个,user对象的地址的,同时调用多次无参数构成方法()——> 是多例 的。 不像 singleton(默认)的那样是无论是执行多少次,applicationContext.getBean ,还是启动多个线程,都是同一个User对象单例的。

在这里插入图片描述


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testScope {
    @Test
    public void test() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
        User user = applicationContext.getBean("user", User.class);
        User user1 = applicationContext.getBean("user", User.class);
        System.out.println(user);
        System.out.println(user1);

        // 启动多线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                User user2 = applicationContext.getBean("user", User.class);
                User user3 = applicationContext.getBean("user", User.class);
                System.out.println(user2);
                System.out.println(user3);
            }
        }).start();

    }


}

1.4 Spring 中的 bean 标签当中scope= 属性其他的值说明

scope属性的值不止两个,它一共包括8个选项:

      1. singleton:默认的,单例。
      2. prototype:原型。每调用一次getBean()方法则获取一个新的Bean对象。或每次注入的时候都是新对象。
      3. request:一个请求对应一个Bean。仅限于在WEB应用中使用
      4. session:一个会话对应一个Bean。仅限于在WEB应用中使用
      5. global sessionportlet应用中专用的。如果在Servlet的WEB应用中使用global session的话,和session一个效果。(portlet和servlet都是规范。servlet运行在servlet容器中,例如Tomcat。portlet运行在portlet容器中。)
      6. application:一个应用对应一个Bean。仅限于在WEB应用中使用。
      7. websocket:一个websocket生命周期对应一个Bean。仅限于在WEB应用中使用。
      8. 自定义scope:很少使用。

特殊说明: 如果大家,进行了一个实践测试代码,可能会发现,IDE工具,仅仅只提示了 scope属性值的两个值(singleton,prototype)。就算我们自己手动敲出了其他的值,也是会报 。如下图所示:

在这里插入图片描述

在这里插入图片描述

哈哈哈,这个IDE不给我们提示就算了,还给我们报错。

其实这个并不是IDE工具的问题,而是,我们其他的对应的scope其他属性的值,是需要在特定的情况下才有用的。比如:我们这里的 request 是需要在 web 项目当中才是有用的 ,所以 IDE才给我们来了这么一个错误——》爆红了。

我们可以,在 pom.xml 项目配置文件上,加上一个web 框架,比如:这里我们加上SpringMVC 就可以了。试试

在这里插入图片描述

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.18</version>
        </dependency>

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.rainbowsea</groupId>
    <artifactId>spring6-007-circular-dependency</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.11</version>
        </dependency>


        <!-- junit4 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.18</version>
        </dependency>

    </dependencies>

</project>

在这里插入图片描述

1.5 自定义作用域,一个线程一个 Bean

接下来咱们自定义一个Scope,关于线程级别的Scope,

作用:在同一个线程中,获取的Bean都是同一个。跨线程则是不同的对象。

  • 第一步:自定义Scope。(实现Scope接口)

  • spring内置了线程范围的类:org.springframework.beans.factory.config.CustomScopeConfigurer,和 org.springframework.context.support.SimpleThreadScope可以直接用。

    • 第二步:将自定义的Scope注册到Spring容器中。

在这里插入图片描述

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
  <property name="scopes">
    <map>
      <entry key="myThread">
        <bean class="org.springframework.context.support.SimpleThreadScope"/>
      </entry>
    </map>
  </property>
</bean>
<?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 class="org.springframework.beans.factory.config.CustomScopeConfigurer">
        <property name="scopes"> <!-- set 注入,为该类当中的 name 属性赋值-->
            <map> <!-- map集合 注入,为该类当中的 key 属性赋值,也就是我们自定义的 scope的属性值的名字-->
                <entry key="myThread">
                    <bean class="org.springframework.context.support.SimpleThreadScope"/>
                </entry>
            </map>
        </property>
    </bean>



    <bean name="user" class="com.rainbowsea.spirngBean.User" scope="myThread"></bean>
</beans>

我们还是使用 User 这个类,作为 Bean 进行一个测试。

在这里插入图片描述

启动多个线程,处理。

在这里插入图片描述


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testScope {
    @Test
    public void test() {
        // 第一个线程
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
        User user = applicationContext.getBean("user", User.class);
        User user1 = applicationContext.getBean("user", User.class);
        System.out.println(user);
        System.out.println(user1);

        // 启动多线程
        // 第二个线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                User user2 = applicationContext.getBean("user", User.class);
                User user3 = applicationContext.getBean("user", User.class);
                System.out.println(user2);
                System.out.println(user3);
            }
        }).start();

    }
}

从结果上,我们可以看出:

一个线程,调用了一次无参构造方法(),生产一个对象。

成功实现了。在同一个线程中,获取的Bean都是同一个。跨线程则是不同的对象。

2. 总结:

  1. 默认情况下,Spring的IoC容器创建的Bean对象是单例的。默认是singleton(单例的)
  2. 可以在bean标签中指定scope属性的值为:**prototype(多例),默认是singleton(单例的) **
  3. 同时要注意:scope属性的值不止两个,它一共包括8个选项:,其他的要在特定的配置下,才能使用,例如:request和session 要是在 web 框架才可以使用。

3. 最后:

“在这个最后的篇章中,我要表达我对每一位读者的感激之情。你们的关注和回复是我创作的动力源泉,我从你们身上吸取了无尽的灵感与勇气。我会将你们的鼓励留在心底,继续在其他的领域奋斗。感谢你们,我们总会在某个时刻再次相遇。”

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1646139.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

AI视频教程下载:用 ChatGPT 和 WordPress 创建赚钱网站

您是否有兴趣开设网站&#xff08;博客&#xff09;&#xff0c;但不知道从何入手&#xff1f; 或者您已经开设了网站&#xff08;博客&#xff09;&#xff0c;但难以从中获利&#xff1f; 别找啦&#xff01; 本课程旨在教授您使用 WordPress 创建成功盈利网站&#xff08;博…

如何让你的排单更快?

一般我们都喜欢做打板借用快速通道&#xff01;但是目前快速通道也是共享通道&#xff0c;独立单元格基本不开发。 想要排单更快&#xff0c;想要隔夜打板&#xff0c;我们到底应该怎么做呢&#xff1f; 想要排单更快&#xff0c;说白了就是要提高你的交易速度&#xff01;一&a…

设计模式Java实现-建造者模式

楔子 小七在2019年的时候&#xff0c;就想写一个关于设计模式的专栏&#xff0c;但是最终却半途而废了。粗略一想&#xff0c;如果做完一件事要100分钟&#xff0c;小七用3分钟热情做的事&#xff0c;最少也能完成10件事情了。所以这一次&#xff0c;一定要把他做完&#xff0…

有人问,Windows 内核和 Linux 内核谁更复杂?

在开始前我有一些资料&#xff0c;是我根据网友给的问题精心整理了一份「 Linux的资料从专业入门到高级教程」&#xff0c; 点个关注在评论区回复“888”之后私信回复“888”&#xff0c;全部无偿共享给大家&#xff01;&#xff01;&#xff01; 作为一个读过两者源码并写过…

基于Springboot的果蔬作物疾病防治系统(有报告)。Javaee项目,springboot项目。

演示视频&#xff1a; 基于Springboot的果蔬作物疾病防治系统&#xff08;有报告&#xff09;。Javaee项目&#xff0c;springboot项目。 项目介绍&#xff1a; 采用M&#xff08;model&#xff09;V&#xff08;view&#xff09;C&#xff08;controller&#xff09;三层体系…

基于JSP的酒店客房管理系统(三)

目录 第四章 系统各模块的实现 4.1客房管理系统首页的实现 4.1.1 客房管理系统首页概述 4.2客房管理系统前台的实现 4.2.1 客房管理系统前台概述 4.2.2 客房管理系统前台实现过程 4.2.3 预定客房信息及客房信息的查询 4.3客房管理系统后台的实现 4.3.1 客房管理系统后…

认识ansible 了解常用模块

ansible是什么&#xff1f; Ansible是一个基于Python开发的配置管理和应用部署工具&#xff0c;现在也在自动化管理领域大放异彩。它融合了众多老牌运维工具的优点&#xff0c;Pubbet和Saltstack能实现的功能&#xff0c;Ansible基本上都可以实现。是自动化运维工具&#xff0…

【Scala---01】Scala简介与环境部署『 Scala简介 | 函数式编程简介 | Scala VS Java | 安装与部署』

文章目录 1. Scala简介2. 函数式编程简介3. Scala VS Java4. 安装与部署 1. Scala简介 Scala是由于Spark的流行而兴起的。Scala是高级语言&#xff0c;Scala底层使用的是Java&#xff0c;可以看做是对Java的进一步封装&#xff0c;更加简洁&#xff0c;代码量约是Java的一半。…

【Osek网络管理测试】[TG3_TC6]等待总线睡眠状态_2

&#x1f64b;‍♂️ 【Osek网络管理测试】系列&#x1f481;‍♂️点击跳转 文章目录 1.环境搭建2.测试目的3.测试步骤4.预期结果5.测试结果 1.环境搭建 硬件&#xff1a;VN1630 软件&#xff1a;CANoe 2.测试目的 验证DUT在满足进入等待睡眠状态的条件时是否进入该状态 …

【搜索技能】外链

文章目录 前言一、外链是什么&#xff1f;二、如何进行外链调查&#xff1f;总结 前言 今儿因为在搜索一个很感兴趣的软件&#xff0c;但是软件信息所在的网址非常有限。因此产生了一个念头&#xff1a;我能不能找到所有的包含了或者是引用了这个网站的网站呢? 调查之下&…

C语言动态内存管理malloc、calloc、realloc、free函数、内存泄漏、动态内存开辟的位置等的介绍

文章目录 前言一、为什么存在动态内存管理二、动态内存函数的介绍1. malloc函数2. 内存泄漏3. 动态内存开辟位置4. free函数5. calloc 函数6. realloc 函数7. realloc 传空指针 总结 前言 C语言动态内存管理malloc、calloc、realloc、free函数、内存泄漏、动态内存开辟的位置等…

四种网络IO模型

&#x1f4dd;个人主页&#xff1a;五敷有你 &#x1f525;系列专栏&#xff1a;面经 ⛺️稳中求进&#xff0c;晒太阳 IO的定义 IO是计算机内存与外部设备之间拷贝数据的过程。CPU访问内存的速度远高于外部设备。因此CPU是先把外部设备的数据读取到内存&#xff0c;在…

Linux驱动开发——(十一)INPUT子系统

目录 一、input子系统简介 二、input驱动API 2.1 input字符设备 2.2 input_dev结构体 2.3 上报输入事件 2.4 input_event结构体 三、代码 3.1 驱动代码 3.2 测试代码 四、平台测试 一、input子系统简介 input子系统是管理输入的子系统&#xff0c;和pinctrl、gpio子…

微信公众号 点击显示答案 操作步骤

1、右键进入检查模式 2、ctrlf查找html元素 3、添加答案区域代码 添加答案区域代码后&#xff0c;可以直接在页面进行格式调整 <!-- 此处height控制显示区域高度 --> <section style"height: 1500px;overflow-x: hidden;overflow-y: auto;text-align: center;b…

RAG 2.0,让RAG 终成正果

在观察人工智能行业的时候&#xff0c;我们已经习惯了每天看到各种事物被“淘汰”。有时候&#xff0c;当我不得不第23923次谈论某个事物突然被“淘汰”时&#xff0c;我自己也会感到不安。 然而&#xff0c;像Contextual.ai提出的基于情境语言模型&#xff08;CLMs&#xff0…

AI预测体彩排3第3套算法实战化赚米验证第2弹2024年5月6日第2次测试

由于今天白天事情比较多&#xff0c;回来比较晚了&#xff0c;趁着还未开奖&#xff0c;赶紧把预测结果发出来吧~今天是第2次测试~ 2024年5月6日排列3预测结果 6-7码定位方案如下&#xff1a; 百位&#xff1a;2、3、1、5、0、6 十位&#xff1a;4、3、6、8、0、9 个位&#xf…

【数据可视化-02】Seaborn图形实战宝典

Seaborn介绍 Seaborn是一个基于Python的数据可视化库&#xff0c;它建立在matplotlib的基础之上&#xff0c;为统计数据的可视化提供了高级接口。Seaborn通过简洁美观的默认样式和绘图类型&#xff0c;使数据可视化变得更加简单和直观。它特别适用于那些想要创建具有吸引力且信…

微信视频号如何变现呢,视频号涨粉最快方法

今天给大家带来的是视频号分成计划 视频号流量主这个项目&#xff0c;可以说这是目前的一个蓝海赛道&#xff0c;做的人也少&#xff0c;外面开的培训也很少&#xff0c;作为副业还是比较适合个人的&#xff0c;如果想批量操作这个项目&#xff0c;也比较适合工作室的。而且这…

【CTF Web】XCTF GFSJ0485 simple_php Writeup(代码审计+GET请求+PHP弱类型漏洞)

simple_php 小宁听说php是最好的语言,于是她简单学习之后写了几行php代码。 解法 &#xfeff;<?php show_source(__FILE__); include("config.php"); $a$_GET[a]; $b$_GET[b]; if($a0 and $a){echo $flag1; } if(is_numeric($b)){exit(); } if($b>1234){ech…

Python学习笔记------处理数据和生成折线图

给定数据&#xff1a; jsonp_1629344292311_69436({"status":0,"msg":"success","data":[{"name":"美国","trend":{"updateDate":["2.22","2.23","2.24",&qu…