基于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>
相关推荐
ChoSeitaku21 小时前
NO.4|protobuf网络版通讯录|httplib|JSON、XML、ProtoBuf对比
xml·json
弹简特2 天前
【JavaEE19-后端部分】 MyBatis 入门第三篇:使用XML完成增删改查
xml·mybatis
spencer_tseng2 天前
Tomcat server.xml <Connector> address=“0.0.0.0“
xml·tomcat
常利兵3 天前
Android 字体字重设置:从XML到Kotlin的奇妙之旅
android·xml·kotlin
Predestination王瀞潞4 天前
2.4 编码->W3C XML 1.0标准(W3C Recommendation):XML(Extensible Markup Language)
xml·前端
青槿吖4 天前
【保姆级教程】Spring事务控制通关指南:XML+注解双版本,避坑指南全奉上
xml·java·开发语言·数据库·sql·spring·mybatis
北京聚信万通科技有限公司5 天前
Odette OFTP2 Group1/2/3深度解读:PDX XML能力划分与选型指南
xml·edi·电子数据交换·as2·国产软件·oftp2
小趴蔡ha7 天前
如何将XML格式标注文件转换为YOLO格式进行目标检测训练(附代码)
xml·yolo·目标检测
__Yvan7 天前
解决ConstraintLayout中LinearLayout显示异常问题
android·xml·约束布局
weixin_307779137 天前
构建健壮的XML文档抓取与摘要流水线:Requests + urllib3.Retry + lxml 实践
xml·开发语言·python·算法·性能优化