Spring创建单例bean

Spring创建bean是有一个Scope。默认是单例。
如何证明Spring创建的Bean就是单例?Spring单例有什么意义在?

Spring创建的bean是否是单例很好判断:

ApplicationContext context = new ClassPathXmlApplicationContext("spring-mvc.xml");

HelloWorld helloWorld = (HelloWorld) context.getBean("helloScope");
HelloWorld helloWorld2 = (HelloWorld) context.getBean("helloScope");
System.out.println(helloWorld);
System.out.println(helloWorld2);

通过以上代码,可以直接输入所创建bean的哈希值,对比两个哈希值可以得出,两个bean指针指向的是同一个对象。
由此得出Spring创建的是单例bean。

通过得出Spring创建的是单例bean其实就可以得出很多用法,例如在类中声明一个List集合,里面的值其实是可以共用的
即helloWorld和hellWord2共享一个List(这不是废话么)

扩充一下,Spring的scope的值有“Singleton/prototype/request/session/global session”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值