基于Xml方式的Bean的配置-Bean的作用范围scope配置

SpringBean的配置详解

  • Bean的配置范围

    • 默认情况下(基本的Spring环境),单纯Spring环境Bean的作用范围有两个:Singleton和prototype
    • singleton :单例,默认值,Spring容器创建的时候,就会进行Bean的实例化 ,并储存到Bean的内部的单例池中,每次getBean时都是从单例池中获取相同的Bean实例
    • prototype :原型,Spring容器初始化时不会创建Bena实例,当调用getBean时 才会实例化Bean,每次getBean都会创建一个新的Bean实例
  • 当scope=singleton时
    *

    XML 复制代码
        <bean id="userService" class="com.example.Service.Impl.UserServiceImpl" scope="singleton">
    java 复制代码
            ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
            Object userService1 = context.getBean("userService");
            Object userService2 = context.getBean("userService");
            Object userService3 = context.getBean("userService");
            System.out.println(userService1);
            System.out.println(userService2);
            System.out.println(userService3);
    • 运行结果如下:

  • 当scope=prototype时

    java 复制代码
        <bean id="userService" name="aaa,bbb" class="com.example.Service.Impl.UserServiceImpl" scope="prototype">
    java 复制代码
            ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
            Object userService1 = context.getBean("userService");
            Object userService2 = context.getBean("userService");
            Object userService3 = context.getBean("userService");
            System.out.println(userService1);
            System.out.println(userService2);
            System.out.println(userService3);
    • 运行结果

PS:如果添加了SpringWebMVC依赖,scope的值就有多个

XML 复制代码
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.7</version>
        </dependency>
相关推荐
l1t1 天前
DuckDB新版rusty_sheet 插件测试
xml·数据库·rust·插件·xlsx·duckdb
l1t1 天前
美团龙猫(longcat.AI)编写的利用二分查找优化Excel的sheet.xml指定范围输出C程序
xml·c语言·excel·解析器
LB21122 天前
MyBatis xml配置文件
xml·java·mybatis
霜绛3 天前
Unity:XML笔记(一)——Xml文件格式、读取Xml文件、存储修改Xml文件
xml·笔记·学习·unity·游戏引擎
fatiaozhang95273 天前
晶晨线刷工具下载及易错点说明:生成工作流程XML失败
android·xml·网络·电视盒子·刷机固件·机顶盒刷机
l1t3 天前
利用DeepSeek编写验证xlsx格式文件中是否启用sharedStrings.xml对读写效率影响python程序
xml·开发语言·python·算法·xlsx
Wins_calculator5 天前
解决Visual Studio中UWP设计器无法显示的问题:需升级至Windows 11 24H2
xml·ide·windows·visual studio
MediaTea6 天前
Python 第三方库:lxml(高性能 XML/HTML 解析与处理)
xml·开发语言·前端·python·html
CodeCraft Studio7 天前
PPT处理控件Aspose.Slides教程:使用 C# 编程将 PPTX 转换为 XML
xml·c#·powerpoint·aspose·ppt转xml·ppt文档开发