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