• Spring 框架学习(六)---- Bean作用域


    Spring 框架学习(六)---- Bean作用域


      经过前面的学习,我们可以知道bean是存在作用域的。

      从spring的官方文档中发现spring支持六种作用域,我们只需要重点认识singleton、protoType即可,后面的作用域都是于web框架相关的。


    在这里插入图片描述


    一、singleton(单例模式)


    在这里插入图片描述


      就和图中的一样,如果bean的作用域为singleton,那么在IOC容器中只有每个bean只有一个唯一的实例被创建。

    我们通过代码来认识一下,bean的单例模式

    bean的作用域默认是singleton,我们也可以手动通过在xml的bean中scope进行设置。

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="user" class="pojo.User" scope="singleton"/>
    
    </beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    根据同一个bean 获取两次实例,查看实例是否相同

        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            User user1 = context.getBean("user", User.class);
            User user2 = context.getBean("user",User.class);
            System.out.println(user1==user2);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    查看运行结果

    在这里插入图片描述

    说明 这个Bean的作用域是单例模式,根据这个bean只能创建一个唯一的实例。


    二、protoType(原型模式)


    在这里插入图片描述


    就和图中的一样,如果bean的作用域为protoType,那么在IOC容器中每个bean都可以创建多个实例。

    我们通过代码来认识一下,bean的原型模式

    bean的作用域默认是singleton,我们也可以手动通过在xml的bean中scope进行设置成 protoType。

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="user" class="pojo.User" scope="prototype"/>
    
    </beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    根据同一个bean 获取两次实例,查看实例是否相同

        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            User user1 = context.getBean("user", User.class);
            User user2 = context.getBean("user",User.class);
            System.out.println(user1==user2);
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    查看运行结果

    在这里插入图片描述

    说明了当设置bean为 protoType时,一个bean可以创建多个不同的实例。

  • 相关阅读:
    LeetCode 2296.设计一个文本编辑器
    Spring Cloud Alibaba 2021.0.1.0 发布:版本号再也不迷糊了
    「深入理解」缓存更新策略及缓存不一致问题解决方案
    【51单片机】51单片机概述(学习笔记)
    Nautilus Chain全球行分享会,上海站圆满举办
    一名优秀的软件测试人员,需要掌握哪些技能?
    网络安全(黑客)自学
    Linux系统中安装Redis-7.0.4
    linux入门---消费者生产者的模拟实现
    Linux--CE--ansible常用模块(1)
  • 原文地址:https://blog.csdn.net/rain67/article/details/125324625