Spring中的单例和多例
在Spring中,bean可以被定义为两种模式:prototype(多例)和singleton(单例)
singleton(单例):只有一个共享的实例存在,所有对这个bean的请求都会返回这个唯一的实例。
prototype(多例):对这个bean的每次请求都会创建一个新的bean实例,类似于new。
Spring bean 默认是单例模式。
-
单例测试
测试类
public class User {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
xml文件
<bean id="u" class="com.demo.singleton.User" scope="singleton">
<property name="name" value="张三"></property>
<property name="age" value="20"></property>
</bean>
测试输出
String config = "spring/ApplicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
User user1 = (User)ac.getBean("u");
User user2 = (User)ac.getBean("u");
System.out.println(user1);
System.out.println(user2);
结果
发现,bea类型为singleton时,即使生成俩个类,但是他们的内存地址确实一样的,也就是说,singleton的内存地址不随着生成数量的多寡改变
-
多例测试
测试类
public class People {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
xml文件
<bean id="people" class="com.demo.singleton.People" scope="prototype">
<property name="name" value="李四"></property>
<property name="age" value="21"></property>
</bean>
测试
String config = "spring/ApplicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
People people1 = (People)ac.getBean("people");
People people2 = (People)ac.getBean("people");
System.out.println(people1);
System.out.println(people2);
结果
发现生成一个类,他的内存地址就会变化一次
-
总结
个人理解:单例和多例的主要区别是内存地址是否改变,单例的内存地址一定不会改变,多例的内存地址不一定不变,当他每次被请求一次的时候就会生成新的,但是不被重新请求就不会变