Spring中bean属性: Singleton和Prototype的区别

1、XML中的配置

    // 当scope为singleton时
   
        
   

 

  // 当scope为prototype时
   
        
   

 

2、测试代码

@Test
    public void test() {
        
        ApplicationContext appContext = new ClassPathXmlApplicationContext("beans.xml");
        People people1 = appContext.getBean("people", People.class);
        People people2 = appContext.getBean("people", People.class);
        

        System.out.println(people1);
        System.out.println(people2);
        System.out.println(people1==people2);
        
    }

 

3、 测试结果

 3.1 Singleton的测试结果


  Id: 1
  Name: 群演 
}

  Id: 1
  Name: 群演 
}
true

3.2 Prototype的测试结果


  Id: 1
  Name: 群演 
}

  Id: 2
  Name: 群演 
}
false

 

4. 测试类

package cyz.method.injection;

public class People {
    private String name;
    private int printId;
    private static int id = 0;
    
    
    public People() {
        id++;
        printId=id;
    }
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    
    public String toString() {
        
        return "{ \n  Id: " + printId + "\n  Name: " + name + " \n}";
    }
    
}
 

5. 总结

  当bean的scope为singleton时,Spring容器仅创建一个对象,当下次获取的时候还是第一次创建出来的对象,且获取的对象引用也相同。当使用 == 符号判断两个获取的对象时,得到的结果为true。

  当bean的scope为prototype是,Spring容器在用户获取该对象是创建一个新的对象。每次获取都创建一个全新的对象给用户操作。

 

 

你可能感兴趣的:(Spring中bean属性: Singleton和Prototype的区别)