天天看点

spring bean的作用域:singleton和prototype的区别

先做一个实验

xml配置文件配置一个bean

<bean id="car" class="com.beans.relation.Car">
      <property name="brand" value="Audi"></property>
      <property name="price" value="2222222"></property>
  </bean>      

然后在运行主类里面创建两个car对象

Car car=(Car) ctx.getBean("car");
Car car2=(Car) ctx.getBean("car");
System.out.println(car==car2);      

运行

spring bean的作用域:singleton和prototype的区别

运行结果为true,说明这两个是一样的。因为默认的是单例的。

如果改变这个bean的作用域,就是false而不是true了

<!-- 使用bean的scope属性来配置bean的作用域
  singleton:默认值,容器初始化时创建bean实例,在整个容器的生命周期内只创建一个bean,单例的
   -->
  <bean id="car" class="com.beans.relation.Car" scope="prototype">
      <property name="brand" value="Audi"></property>
      <property name="price" value="2222222"></property>
  </bean>      

这个bean不是单例的,就是每次向容器获取一个bean的时候都会产生一个新的bean。

我们来加深一下理解;

把bean的作用域改为singleton,然后在Car类里面写一个无参的构造方法。

public Car() {
      super();
      // TODO Auto-generated constructor stub
      System.out.println("Car's constructor....");
    }      

在运行主类里面,把几行代码注释掉

ApplicationContext ctx=new ClassPathXmlApplicationContext("scope.xml");
/*Car car=(Car) ctx.getBean("car");
        Car car2=(Car) ctx.getBean("car");
        
        System.out.println(car==car2);
      */      

运行发现,在创建容器的时候,bean就已经被创建好了。

spring bean的作用域:singleton和prototype的区别

但是在改变bean的作用域之后,改为prototype后,发现不行了,并没有语句输出。

将运行主类里面的注释拿掉。再次运行。

Car car=(Car) ctx.getBean("car");
        Car car2=(Car) ctx.getBean("car");
        
        System.out.println(car==car2);