【spring】--Bean作用域

  Spring框架功能强大,其中一个常用的功能是使用IOC容器来管理Bean,在创建Bean的过程中,主要有5中作用域,下面就来介绍一下每一个作用域的特点和作用。

  1、Singleton:设置为该模式的Bean,容器初始化时就创建一个Bean实例,而且该实例只存在一份。测试如下:

   创建SingleScope类:    

 

public class SingleScope {
    
    //创建空构造函数,用于测试IOC容器初始化时就创建该实例bean
    public SingleScope(){        
        System.out.println("Constructor go ---->");
    }
}

   

 

  配置spring的配置文件ApplicationContext-scope.xml:   

 



    
    

 

 

  创建测试类:    

 

public class ScopeTest {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext-scope.xml");
        
        SingleScope singleScope= (SingleScope) context.getBean("singleScope");
        SingleScope singleScope1= (SingleScope) context.getBean("singleScope");
        System.out.println(singleScope==singleScope1);
    }
}

 

 

  结果如下:

   【spring】--Bean作用域_第1张图片


   需要注意的是:spring中bean的singleton模式与设计模式中的单例模式是两个不同的概念,他们是有相同的特点,只实例一次。但是设计模式中的单例模式指的是ClassLoader加载该类时,只实例化一次。而bean的singleton模式指的是Spring IOC容器中只存在一份该bean。


 2、Prototype:可以存在多个bean实例,容器初始化时不会创建bean实例,使用时才会创建。来看一下测试代码:

  创建PrototypeScope类:   

 

/**
 * Created by 王朋波 on 16/07/2017.
 */
public class PrototypeScope {
    public PrototypeScope(){
        System.out.println("PrototypeScope constructor go --->");
    }
}

 

 

  在spring的配置文件中添加如下配置:   

 


    

 

 

   测试代码:    

 

 //当使用bean时,才创建实例。执行完下述获取实例语句,PrototypeScope中的构造函数才会执行
        PrototypeScope prototypeScope= (PrototypeScope) context.getBean("prototypeScope");
        PrototypeScope prototypeScope1= (PrototypeScope) context.getBean("prototypeScope");
        System.out.println(prototypeScope==prototypeScope1);

 

 

   运行结果:

    【spring】--Bean作用域_第2张图片


   注意的地方:Prototype bean被spring容器配置、装载、实例化之后,其生命周期将由自己负责,也就是spring容器不再管理它的生命周期,交给了客户端进行管理。


 比较常用的是singleton和Prototype,下面三种不常用,简单了解一下基本概念和配置方式。

  3、request:对于每次HTTP请求,使用request定义的Bean都将产生一个新实例,即每次HTTP请求将会产生不同的Bean实例。仅在基于web的Spring ApplicationContext情形下有效。

  4、session:对于每次HTTP Session,使用session定义的Bean豆浆产生一个新实例。仅在基于web的Spring ApplicationContext情形下有效。 

  5、每个全局的HTTP Session,使用session定义的Bean都将产生一个新实例。典型情况下,仅在使用portlet context的时候有效。仅在基于web的Spring ApplicationContext情形下有效。

  上述三种方式除了配置spring的配置文件之外,还需要在web.xml文件增加一个监听设置,如下: 

 


org.springframework.web.context.request.RequestContextListener
  

 

 

  小结:

   bean的作用域中,需要重点掌握Singleton和Prototype两种方式,另外还需要与Struts2中配置Action时,也有这两种模式作对比,明白各自的含义以及默认使用。

  

 

转载于:https://www.cnblogs.com/victor-grace/p/7253609.html

你可能感兴趣的:(设计模式,web.xml,java)