1.默認狀況下,bean的做用域是單例模式,以下app
<bean id="car" class="com.test.autowired.Car" scope="singleton"> <property name="brand" value="Audi"></property> <property name="price" value="300000"></property> </bean>
main方法以下prototype
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContextRelationxml.xml"); Car car = (Car) ctx.getBean("car"); Car car2 = (Car) ctx.getBean("car"); System.out.println(car == car2);
備註:單例模式下,執行完這行代碼code
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContextRelationxml.xml");
構造器方法已經執行了,接着即是從ctx中連續取同一個對象兩次,所以,打印出的結果是true。
2.原型模式xml
<bean id="car" class="com.test.autowired.Car" scope="prototype"> <property name="brand" value="Audi"></property> <property name="price" value="300000"></property> </bean>
main方法同上
啓動項目時,以下代碼不會執行對象
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContextRelationxml.xml");
只有當執行以下代碼時作用域
Car car = (Car) ctx.getBean("car");
纔會建立對象,所以這種狀況會產生兩個對象,因此輸出false。get