zoukankan      html  css  js  c++  java
  • Spring——Bean的作用域

    Spring中Bean的作用域有五种,分别是singleton、prototype、request、session、globalSession。其中request、session、globalSession这三个作用域只有在web开发中才会使用到。

    当在 Spring 中定义一个bean时,你必须声明该 bean 的作用域的选项,若没有声明则默认作用域是singleton。

    1 singleton 该作用域将 bean 的定义的限制在每一个 Spring IoC 容器中的一个单一实例。

    *使用:什么都不做,默认就是单例模式,但是你也可以显示的加一个scope,例如:

    <bean id="user" class="com.zhbit.pojo.User" scope="singleton"/>

    如果你还是不明白什么是单例模式,那就举个例子来说明:

        @Test
        public void test(){
            ApplicationContext context = new ClassPathXmlApplicationContext("beans2.xml");
            User user = context.getBean("user", User.class);
            User user2 = context.getBean("user", User.class);
            System.out.println(user==user2);
        }

    运行结果:

    输出结果为true。证明了user和user2是同一个对象!

    结论:只要bean的作用域是singleton ,getBean()方法中参数用的是同一个bean的id,则实例化的就是对象就是同一个。

    2 prototype,在每次请求获取Bean的时候,都会创建一个新的实例,它在容器初始化的时候不会创建实例,采用的是延迟加载的形式注入Bean,当你使用的时候,才会进行实例化,每次实例化获取的对象都不是同一个 。
    *使用:
       <bean id="user" class="com.kuang.pojo.User" scope="prototype"/>

     举例证明:

        @Test
        public void test(){
            ApplicationContext context = new ClassPathXmlApplicationContext("beans2.xml");
            User user = context.getBean("user", User.class);
            User user2 = context.getBean("user", User.class);
            System.out.println(user==user2);
        }
    }
    运行结果:

    输出结果为false,证明 user和user2不是同一个对象。

    3 request,在每一次http请求时会创建一个实例,该实例仅在当前http request有效
    4 session,在每一次http请求时会创建一个实例,该实例仅在当前http session有效
    5 globalSession,全局Session,供不同的portlet共享,portlet好像是类似于servlet的Web组件
  • 相关阅读:
    C# 文件类的操作---删除
    C#实现Zip压缩解压实例
    UVALIVE 2431 Binary Stirling Numbers
    UVA 10570 meeting with aliens
    UVA 306 Cipher
    UVA 10994 Simple Addition
    UVA 696 How Many Knights
    UVA 10205 Stack 'em Up
    UVA 11125 Arrange Some Marbles
    UVA 10912 Simple Minded Hashing
  • 原文地址:https://www.cnblogs.com/bear7/p/12530699.html
Copyright © 2011-2022 走看看