bean的单例

通过改变中的scope属性,默认是singleton单例。而prototype则指定每getbean得到的都是不同实例。

验证代码:

①:验证默认singleton

//验证<bean id="student" class="entity.Student" >

        @Test
	public void test(){
		String str="applicationContext.xml";
		ApplicationContext ac=
			new ClassPathXmlApplicationContext(str);
		Student s =ac.getBean("student",Student.class);
		Student s1 =ac.getBean("student",Student.class);	
		System.out.println(s==s1);
	}

结果是:true

②验证prototype

//验证<bean id="student" class="entity.Student"   scope="prototype">

        @Test
	public void test(){
		String str="applicationContext.xml";
		ApplicationContext ac=
			new ClassPathXmlApplicationContext(str);
		Student s =ac.getBean("student",Student.class);
		Student s1 =ac.getBean("student",Student.class);	
		System.out.println(s==s1);
	}

结果是:false

也可以打印两个对象的hashcode看是否相同。

原文地址:https://www.cnblogs.com/hts-technology/p/7238288.html