Spring之Bean的作用域

所有的Spring Bean默认都是单例。也就是说,我们每次通过容器获得的实例都是Bean的同一个实例,究竟是不是呢?我们通过代码实验就可以知道。

Student类:

package com.zhushuai.spring;

public class Student {
	int id;
	String name;
	String sex;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	
	

}

client类:

package com.zhushuai.spring;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BeanFactory beanfactory = new ClassPathXmlApplicationContext("applicationContext.xml");
		Student student1 = (Student)beanfactory.getBean("student");
	    System.out.println("student1:"+student1.hashCode());
	    
	    Student student2 = (Student)beanfactory.getBean("student");
	    System.out.println("student2:"+student2.hashCode());
	    
	    System.out.println("student1=student2:"+(student1.equals(student2)));
	    
	    Student student3 = new Student();
	    System.out.println("student3:"+student3.hashCode());
	    
	    Student student4 = new Student();
	    System.out.println("student4:"+student4.hashCode());
		
	    System.out.println("student3=student4:"+(student3.equals(student4)));
	    

	}

}

输出结果:

Spring之Bean的作用域_第1张图片


那如何覆盖Spring的单例配置呢?

当Spring配置bean时候,我们可以为bean配置作用域:

<bean id="student" class="com.zhushuai.spring.Student" scope="prototype">
<property name="id" value="21"></property>
<property name="name" value="zhushuai"></property>
<property name="sex" value="man"></property>
</bean>

配置scope="prototype"作用域后,输出结果就不一样了:



Spring之Bean的作用域_第2张图片



你可能感兴趣的:(Spring之Bean的作用域)