基于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>
相关推荐
阿华的代码王国1 天前
【Android】CheckBox实现和监听
android·xml·java
阿华的代码王国1 天前
【Android】按钮的使用
android·xml·java
浮江雾2 天前
XXE漏洞1-XXE 漏洞简介-XML 语法-DTD 讲解-外部实体讲解
xml·安全·web安全·漏洞·xxe
代码的余温2 天前
XML vs JSON:核心区别与最佳选择
xml·服务器·json
Raners_2 天前
【Java代码审计(2)】MyBatis XML 注入审计
xml·java·安全·网络安全·mybatis
超级小忍5 天前
在 Spring Boot 中使用 MyBatis 的 XML 文件编写 SQL 语句详解
xml·spring boot·mybatis
你我约定有三5 天前
spring--xml注入时bean的property属性
xml·java·spring
12345,catch a tiger5 天前
实用技巧 Excel 与 XML互转
xml
24kHT5 天前
xml映射文件的方式操作mybatis
xml·mybatis
石头wang6 天前
xml 知识总结: xsd,xsi:schemaLocation,xmlns,xmlns:xsi
xml