【Spring】Spring中的单例和多例

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);

结果
在这里插入图片描述
发现生成一个类,他的内存地址就会变化一次


  • 总结
    个人理解:单例和多例的主要区别是内存地址是否改变,单例的内存地址一定不会改变,多例的内存地址不一定不变,当他每次被请求一次的时候就会生成新的,但是不被重新请求就不会变
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值