包括Singleton、Prototype、Request, Session, Application, WebSocket,這邊主要講經常使用的Singleton和Prototype。spring
當定義一個bean爲單例對象時,IoC容器只建立該bean對象的一個實例。這個bean對象存儲在容器的緩存(map)中,後續的對該bean的引用,都是從緩存中取(map.get)。
這個單例跟設計模式的單例模式是不同的。spring的單例是指在容器中僅有一個實例,而設計模式的單例是在JVM進程中僅有一個實例。設計模式
當須要每次getBean的時候,都返回不一樣的實例,這個時候,就須要用Prototype。緩存
若是bean是無狀態的,就須要用Singleton,若是是有狀態的,就用Prototype。
對於Singleton的bean,spring容器會管理他的整個生命週期。
對於Prototype的bean,spring容器無論理他的整個生命週期,儘管初始化的方法會被調用,可是與scope的範圍無關。並且容器關閉時不會調用銷燬方法。app
XML配置:測試
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="singletonBean" class="com.learn.beanScope.SingletonBean" scope="singleton"/> <bean id="prototypeBean" class="com.learn.beanScope.PrototypeBean" scope="prototype"/> </beans>
測試代碼spa
@Test public void test() { ApplicationContext app = new ClassPathXmlApplicationContext("beanScope.xml"); SingletonBean singletonBean1 = app.getBean("singletonBean",SingletonBean.class); SingletonBean singletonBean2 = app.getBean("singletonBean",SingletonBean.class); PrototypeBean prototypeBean1 =app.getBean("prototypeBean",PrototypeBean.class); PrototypeBean prototypeBean2 =app.getBean("prototypeBean",PrototypeBean.class); System.out.println(singletonBean1); System.out.println(singletonBean2); System.out.println(prototypeBean1); System.out.println(prototypeBean2); }
運行結果:
做用域爲Singleton的時候,能夠看出,從容器中取了兩次,地址是同樣的,因此是同一個bean。
做用域爲Prototype的時候,能夠看出,從容器中取了兩次,地址是不同的,因此不是同一個bean。prototype
MyConfig設計
@Configuration public class MyConfig { @Bean @Scope("prototype") public PrototypeBean prototypeBean() { return new PrototypeBean(); } @Bean @Scope("singleton") public SingletonBean singletonBean() { return new SingletonBean(); } }
測試代碼code
@Test public void test() { ApplicationContext app = new AnnotationConfigApplicationContext(MyConfig.class); SingletonBean singletonBean1 = app.getBean("singletonBean",SingletonBean.class); SingletonBean singletonBean2 = app.getBean("singletonBean",SingletonBean.class); PrototypeBean prototypeBean1 =app.getBean("prototypeBean",PrototypeBean.class); PrototypeBean prototypeBean2 =app.getBean("prototypeBean",PrototypeBean.class); System.out.println(singletonBean1); System.out.println(singletonBean2); System.out.println(prototypeBean1); System.out.println(prototypeBean2); }
運行結果:
結果同XML。xml