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看是否相同。

posted on 2017-07-26 10:37  天生一对  阅读(577)  评论(0编辑  收藏  举报

导航