基于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>
相关推荐
好学且牛逼的马11 小时前
原生 JDBC + DbUtils + MyBatis 同场景 Demo(C3P0 数据源 XML 配置版)
xml·mybatis
代码栈上的思考11 小时前
MyBatis XML的方式来实现
xml·java·mybatis
Mr.Pascal14 小时前
深度解读一下 springcloud 的 pom.xml 用到的标签
xml·spring boot·spring cloud
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ1 天前
日志打印配置:logback-spring.xml配置;info和error完全区分了,并且按时间拆分了
xml·spring·logback
Android技术之家2 天前
实测:Jetpack Compose 替代 XML 布局,3 步实现高性能界面迁移
xml
汐ya~2 天前
提示词工程:AI 总误解指令?用XML标签提升3倍准确率
xml·人工智能·prompt·提示词工程·大模型llm
hahjee2 天前
libxslt XSLT转换库:鸿蒙PC上的XML转换工具
xml·华为·harmonyos
TH_13 天前
10、xml的CDATA标签之AI模型
xml
拾忆,想起4 天前
Dubbo多协议暴露完全指南:让一个服务同时支持多种通信方式
xml·微服务·性能优化·架构·dubbo
春蕾夏荷_7282977254 天前
c++ 将xml数据写入sqlite数据库
xml·数据库