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”
转载请注明原文地址: https://ju.6miu.com/read-662411.html