(7)Spring學習記錄---Spring_bean(bean的作用域)
阿新 • • 發佈:2018-11-08
singleton
<!--
使用bean的scope屬性來配置bean的作用域:
singleton:預設值。單例模式,容器初始化時建立。在整個容器的生命週期內只建立一個bean。
prototype:原型的。容器初始化時不建立。在每次建立例項物件時創新一個新的bean。
-->
<bean id="car" class="jjh.test.autowire.Car" p:band="baoma" p:price="300000"
scope="singleton"></bean>
ApplicationContext act=new ClassPathXmlApplicationContext("bean-relation.xml"); Car car=(Car)act.getBean("car"); Car car2=(Car)act.getBean("car"); System.out.println(car==car2);
驗證結果
建立了兩個car,只建立了一個bean物件(構造器只被執行一次)
prototype
<bean id="car" class="jjh.test.autowire.Car" p:band="baoma" p:price="300000"
scope="prototype"></bean>
結果
可以看到被執行了兩次