Spring建立單例bean
阿新 • • 發佈:2019-01-04
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”