ClassPathXmlApplicationContext
执行,那么,xml中的容器就会调用无参构造生成对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); User usr = (User)context.getBean("usr"); User usrr = (User) context.getBean("usr"); System.out.println(usr == usrr);
结果为true
三种方式
<bean id="usr2" class="com.jiwei.pojo.User"> <constructor-arg name="name" value="ip"/> <constructor-arg name="age" value="1"/> </bean>
用type, 不推荐, 不用
用index
<bean id="usr3" class="com.jiwei.pojo.User"> <constructor-arg index="0" value="ioc"/> <constructor-arg index="1" value="1"/> </bean>
即:在ClassPathXmlApplicationContext是就有了一份对象,而且只有一份。
User usr = (User)context.getBean("usr"); User usrr = (User) context.getBean("usr"); System.out.println(usr == usrr); // true usrr.change(); // 一起变化的,一块内存 System.out.println(usr == usrr); // true System.out.println(usr.toString()); System.out.println(usrr.toString());
true
true
User{name='Tom', age=19}
User{name='Tom', age=19}