您的位置:首页 > 编程语言 > Java开发

Spring之Bean的作用域

2016-04-27 23:58 549 查看
所有的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的单例配置呢?

当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"作用域后,输出结果就不一样了:





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: