Spring笔记(二):bean的作用域

在bean中配置作用域使用属性scope来设置bean的作用域

  • scope="singleton" 也是bean配置中默认的配置

    bean配置文件代码:

     <bean id="school" class="com.example.demo.entity.School" scope="singleton">
        <property name="schoolName" value="北京大学"></property>
        <property name="schoolAddress" value="北京市海淀区"></property>
    </bean>
    

    java测试代码:

        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-scop.xml");
    
        School school = (School) ctx.getBean("school");
        School school1 = (School) ctx.getBean("school");
    
        System.out.println(school);
        System.out.println(school1);     
    

    运行结果:

    School被创建
    Disconnected from the target VM, address: '127.0.0.1:51820', transport: 'socket'
    com.example.demo.entity.School@4d5650ae
    com.example.demo.entity.School@4d5650ae
    
    Process finished with exit code 0
    

    从上可以看出bean属性scope为singleton时,容器初始化时会创建实例,该容器中对象的实例有且只有一个

  • scope="prototype"

    bean配置:

     <bean id="school1" class="com.example.demo.entity.School" scope="prototype">
        <property name="schoolName" value="清华大学"></property>
        <property name="schoolAddress" value="北京市海淀区"></property>
    </bean>
    

    java测试代码:

     ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-scop.xml");
    
        School school = (School) ctx.getBean("school1");
        School school1 = (School) ctx.getBean("school1");
    
        System.out.println(school);
        System.out.println(school1);
    
    

    运行结果:

    School被创建
    School被创建
    com.example.demo.entity.School@a38c7fe
    com.example.demo.entity.School@6fdbe764
    

    从运行结果可以看出bean属性scope为prototype时,容器初始化时不会创建bean的实例,只有在调用时才会创建bean的实例;

  • scope="request" 和 scope="session"
    这两个属性都是涉及到与对象,一个是resquest域,两一个是session域

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容