Spirng 当中 Bean的作用域

news2024/10/6 1:37:55

Spirng 当中 Bean的作用域

文章目录

  • Spirng 当中 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/1634371.html

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

相关文章

JAVA基础---Stream流

Stream流出现背景 背景 在Java8之前&#xff0c;通常用 fori、for each 或者 Iterator 迭代来重排序合并数据&#xff0c;或者通过重新定义 Collections.sorts的 Comparator 方法来实现&#xff0c;这两种方式对 大数量系统来说&#xff0c;效率不理想。 Java8 中添加了一个…

一款可视化正则表达式工具

regex-vis是一款在线免费且可视化的正则表达式工具 界面图&#xff1a; 只能输入由26个英文字母组成的字符串 ^[A-Za-z]$ 只能输入数字 ^[0-9]*$测试错误 测试正确 快来感受一下叭 官方网址&#xff1a; Regex VisRegex visualizer & editor, make the regular expr…

西门子:HMI小游戏-灰太狼与喜羊羊

DB块&#xff1a; HMI界面&#xff1a; 实际视频&#xff1a; 抓羊小游戏

docker各目录含义

目录含义builder构建docker镜像的工具或过程buildkit用于构建和打包容器镜像&#xff0c;官方构建引擎&#xff0c;支持多阶段构建、缓存管理、并行化构建和多平台构建等功能containerd负责容器生命周期管理&#xff0c;能起、停、重启&#xff0c;确保容器运行。负责镜管理&am…

电脑技巧:推荐一款非常好用的媒体播放器PotPlayer

目录 一、 软件简介 二、功能介绍 2.1 格式兼容性强 2.2 高清播放与硬件加速 2.3 自定义皮肤与界面布局 2.4 多音轨切换与音效增强 2.5 字幕支持与编辑 2.6 视频截图与录像 2.7 网络流媒体播放 三、软件特色 四、使用技巧 五、总结 一、 软件简介 PotPlayer播放器 …

【面试经典 150 | 回溯】括号生成

文章目录 写在前面Tag题目来源解题思路方法一&#xff1a;暴力法方法二&#xff1a;回溯 写在最后 写在前面 本专栏专注于分析与讲解【面试经典150】算法&#xff0c;两到三天更新一篇文章&#xff0c;欢迎催更…… 专栏内容以分析题目为主&#xff0c;并附带一些对于本题涉及到…

compose调用系统分享功能分享图片文件

compose调用系统分享功能图片文件 简介UI界面提供给外部程序的文件访问权限创建FileProvider设置共享文件夹 通用分享工具虚拟机验证结果参考 本系列用于新人安卓基础入门学习笔记&#xff0c;有任何不同的见解欢迎留言 运行环境 jdk17 andriod 34 compose material3 简介 本案…

JAVA面试专题-Redis

你在最近的项目中哪些场景使用了Redis 缓存 缓存穿透 缓存穿透&#xff1a;查询一个不存在的数据&#xff0c;mysql查询不到数据也不好直接写入缓存&#xff0c;导致每次请求都查数据库。 解决方案一&#xff1a;缓存空数据&#xff0c;即使查询返回的数据为空&#xff0c;也把…

xss漏洞学习

1.xss漏洞简介 跨站脚本&#xff08;Cross-Site Scripting&#xff09;&#xff0c;本应该缩写为CSS&#xff0c;但是该缩写已被层叠样式脚本Cascading Style Sheets所用&#xff0c;所以改简称为XSS。也称跨站脚本或跨站脚本攻击。 原理&#xff1a;跨站脚本攻击XSS通过将恶…

SQLite如何处理CSV 虚拟表(三十七)

返回&#xff1a;SQLite—系列文章目录 上一篇&#xff1a;SQLite的DBSTAT 虚拟表&#xff08;三十六&#xff09; 下一篇:SQLite的扩展函数Carray()表值函数(三十八) ​ RFC4180格式是一种文本文件格式&#xff0c;被用于表格数据间的交互&#xff0c;也可将表格数据转化…

Java进阶-JINQ详解与使用

本文详细介绍了JINQ&#xff08;Java Integrated Query&#xff09;&#xff0c;一种强化Java中数据查询能力的库&#xff0c;提供类SQL的查询语法和类型安全的操作。文章首先解释了JINQ的基本功能和应用&#xff0c;随后通过具体示例展示了如何使用JINQ进行数据过滤、投影、连…

Python自学篇3-PyCharm开发工具下载、安装及应用

一、Python开发工具 自学篇1中讲到了安装Python之后出现的几个应用程序&#xff0c;其中IDLE、Python.exe都可以用来编写python程序&#xff0c;也可以进行调试&#xff1b;但是比较基础&#xff0c;比较原始&#xff0c;调试不方便&#xff0c;界面也不友好&#xff0c;需要更…

天空卫士旗舰产品入选《网络安全专用产品指南》

权威认证 近日&#xff0c;中国网络安全产业联盟&#xff08;CCIA&#xff09;发布了第一版《网络安全专用产品指南》。这一权威指南中&#xff0c;天空卫士荣获殊荣&#xff0c;旗下三款尖端产品荣耀入选&#xff0c;分别是增强型Web安全网关&#xff08;ASWG&#xff09;、数…

解析Redis Key Prefix配置之谜:双冒号“::”的由来与作用

前言 在使用Spring Boot集成Redis进行应用开发时&#xff0c;为了增强缓存键的可读性和管理性&#xff0c;我们常常会在配置文件中设定一个全局的key-prefix。如果你发现存储至Redis的键自动附加了“::”&#xff0c;本文将深入探讨这一现象背后的原因&#xff0c;解析Spring …

长难句打卡4.29

If appropriate public policies were in place to help all women—whether CEOs or their children’s caregivers—and all families, Sandberg would be no more newsworthy than any other highly capable person living in a more just society 如果能制定适当的公共政策…

解决Pycharm全局搜索与输入法简繁切换快捷键冲突问题

Pycharm中全局搜索快捷键Ctrl Shift F 如图所示&#xff1a; 微软输入法简繁切换快捷键设置&#xff1a; 解决办法&#xff1a; 关掉输入法的切换功能即可&#xff0c;或者更改简繁切换快捷键&#xff0c;毕竟简繁切换使用频率极低。

智慧农业设备——虫情监测系统

随着科技的不断进步和农业生产的日益现代化&#xff0c;智慧农业成为了新时代农业发展的重要方向。其中&#xff0c;虫情监测系统作为智慧农业的重要组成部分&#xff0c;正逐渐受到广大农户和农业专家的关注。 虫情监测系统是一种基于现代传感技术、图像识别技术和大数据分析技…

Django-admin组件

Django-admin组件 admin是django中提供的一套可视化工具&#xff1a;用于对ORM中定义的表进行增删改查。 1 概览 在django项目启动时&#xff0c;自动找到注册到admin中的所有model中定义的类&#xff0c;然后为这些类生成一系列的URL和视图函数&#xff0c;实现基本增删改查…

202009青少年软件编程(Python)等级考试试卷(一级)

第 1 题 【单选题】 Python自带的编程环境是&#xff1f;&#xff08; &#xff09; A :PyScripter B :Spyder C :Notepad D :IDLE 正确答案:D 试题解析: 第 2 题 【单选题】 假设a2,b3,那么a-b*b的值是&#xff1f;( ) A :-3 B :-2 C :-7 D :-11 正确答案:C 试题…

基于ESP32—CAM物联网WIFI小车

一.功能概述 摄像头的画面可以实时的传输到&#xff0c;点灯科技APP的手机端&#xff0c;这样可以实时查看周围环境的状况&#xff0c;灯光不足&#xff0c;画面不清晰时可以打开灯光照明。手机端有左转、右转、前进、后退、停止的按钮。可以根据自己需要&#xff0c;来控制小车…