• bean的作用域【spring基础】


    1、单例模式 singleton(spring默认机制)

    无论创建多少个Spring IoC容器的bean实例,只要id与bean定义相匹配,就只会返回bean的同一实例【singleton 为默认值】

    <bean id="user2" class="com.wang.pojo.User" c:age="17" c:name="皇上" scope="singleton"/>
    
     @Test
        public void test1(){
            ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
            User user = context.getBean("user2", User.class);
            User user2 = context.getBean("user2", User.class);
            System.out.println(user == user2);
    

    单例模式示意图

    2、原型模式 prototype

    每次从容器中 get到的时候,都会产生一个新对象

    <bean id="user2" class="com.wang.pojo.User" c:age="17" c:name="皇上" scope="prototype"/>
    
        @Test
        public void test1(){
            ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
            User user = context.getBean("user2", User.class);
            User user2 = context.getBean("user2", User.class);
            System.out.println(user == user2);
        }
    

    原型模式示意图

    3、Request

    当一个bean的作用域为Request,表示在一次HTTP请求中,一个bean定义对应一个实例;即每个HTTP请求都会有各自的bean实例,它们依据某个bean定义创建而成。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

     <bean id="loginAction" class=cn.csdn.LoginAction" scope="request"/>
    

    针对每次HTTP请求,Spring容器会根据loginAction bean的定义创建一个全新的LoginAction bean实例,且该loginAction bean实例仅在当前HTTP request内有效,因此可以根据需要放心的更改所建实例的内部状态,而其他请求中根据loginAction bean定义创建的实例,将不会看到这些特定于某个请求的状态变化。当处理请求结束,request作用域的bean实例将被销毁。

    4、Session

    当一个bean的作用域为Session,表示在一个HTTP Session中,一个bean定义对应一个实例。该作用域仅在基于web的Spring ApplicationContext情形下有效。考虑下面bean定义:

     <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>
    

    针对某个HTTP Session,Spring容器会根据userPreferences bean定义创建一个全新的userPreferences bean实例,且该userPreferences bean仅在当前HTTP Session内有效。与request作用域一样,可以根据需要放心的更改所创建实例的内部状态,而别的HTTP Session中根据userPreferences创建的实例,将不会看到这些特定于某个HTTP Session的状态变化。当HTTP Session最终被废弃的时候,在该HTTP Session作用域内的bean也会被废弃掉。

  • 相关阅读:
    漫谈程序猿系列:看看你离优秀有多远
    qt学习笔记(五) QGraphicsPixmapItem与QGraphicsScene的编程实例 图标拖动渐变效果
    DropdownList绑定的两种方法
    JUnit入门
    [rxjs] Async, handle data over time
    [rxjs] Creating An Observable with RxJS
    [Javascript + rxjs] Simple drag and drop with Observables
    [Javascript + rxjs] Using the map method with Observable
    [AngularJS] Extract predicate methods into filters for ng-if and ng-show
    [Javascript + rxjs] Introducing the Observable
  • 原文地址:https://www.cnblogs.com/IanIan/p/14327031.html
Copyright © 2020-2023  润新知