基于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>
相关推荐
R-sz2 天前
mybatis的XML,如何多值匹配,支持单值(=)和多值(IN)查询
xml·mybatis
方芯半导体2 天前
EtherCAT从站控制器芯片(FCE1353)与MCU(STM32H743)功能板解析!
xml·stm32·单片机·嵌入式硬件·物联网·自动化
码农娟2 天前
Hutool XML工具-XmlUtil的使用
xml·java
码农娟3 天前
Hutool XML工具-XmlUtil遇到标签问题
xml
草履虫建模4 天前
A02 Maven 基础配置:本地仓库、镜像、项目编码与常见问题(IDEA 实战)
xml·java·spring boot·spring·maven·intellij-idea·idea
Dawndddddd4 天前
XXE(XML外部实体注入)漏洞
xml·xxe
嵌入式老表4 天前
ISO15118-2 解读4 —— XML、EXI、签名
xml
学海无涯书山有路5 天前
Android LiveData + MVVM 新手入门教程(基于 XML+Java)
android·xml·java
方方洛6 天前
技术实践总结:schema-bridgion:json、xml、yaml、toml文件相互转换
xml·前端·typescript·node.js·json
写代码的【黑咖啡】6 天前
Python中的lxml:高效XML处理库
xml·开发语言·python