基于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>
相关推荐
iSee8579 小时前
struts2 XML外部实体注入漏洞复现(CVE-2025-68493)
xml·安全·struts2
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ2 天前
mapper.xml中的大于等于、小于等于
xml
问水っ3 天前
Qt Creator快速入门 第三版 第17-2章 XML
xml
独断万古他化3 天前
【MyBatis 深度解析】注解操作与 XML 配置:增删改查全流程实现
xml·java·spring·mybatis
odoo中国3 天前
如何在 Odoo 19 中加载演示数据
xml·csv·odoo·odoo 19·odoo 演示数据加载
web守墓人5 天前
【前端】ikun-pptx编辑器前瞻问题五:pptx中的xml命名空间
xml·前端
h7ml5 天前
企业微信回调模式解析:从XML到POJO的自定义JAXB编解码器设计
xml·java·企业微信
Full Stack Developme5 天前
达梦(DM8)对 JSON 与 XML 的使用教程
xml·数据库·json
chilavert3186 天前
技术演进中的开发沉思-304计算机原理:XML
xml·计算机原理
程序猿零零漆7 天前
Spring之旅 - 记录学习 Spring 框架的过程和经验(十一)基于XML方式、注解的声明式事务控制、Spring整合Web环境
xml·学习·spring