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”
新聞熱點
疑難解答