基于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>
相关推荐
椰椰椰耶8 小时前
【MyBatis】XML实现,配置方法和增、删、改、查
xml·oracle·mybatis
旷世奇才李先生1 天前
XML Schema 安装使用教程
xml
ddfa12341 天前
XML 笔记
xml·服务器
一勺菠萝丶2 天前
Spring Boot + MyBatis/MyBatis Plus:XML中循环处理List参数的终极指南
xml·spring boot·mybatis
李少兄14 天前
解决OSS存储桶未创建导致的XML错误
xml·开发语言·python
阳光开朗_大男孩儿14 天前
XML读取和设置例子
xml·java·数据库
悟能不能悟16 天前
在 MyBatis 的xml中,什么时候大于号和小于号可以不用转义
xml·java·mybatis
慌糖16 天前
XML重复查询一条Sql语句??怎么解决
xml·数据库·sql
胖大和尚16 天前
在 XML 节点名称前添加前缀
xml
casual_clover17 天前
Android 中 解析 XML 字符串的几种方式
android·xml