结论:Spring在创建spring容器的时候就创建的类的对象(调用了类的无参构造方法)
1. 下面我们创建一个Person类用于测试
packagecom.mars.learnspring;importcom.sun.xml.internal.ws.addressing.WsaActionUtil;public classPerson {privateString name;privateString gender;privateInteger age;privateString email;publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}publicString getGender() {returngender;
}public voidsetGender(String gender) {this.gender =gender;
}publicInteger getAge() {returnage;
}public voidsetAge(Integer age) {this.age =age;
}publicString getEmail() {returnemail;
}public voidsetEmail(String email) {this.email =email;
}
@OverridepublicString toString() {return "Person{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
", email='" + email + '\'' +
'}';
}
//注意:下面的无参构造方法用于测试publicPerson() {
System.out.println("Person类的无参构造方法...");
}
}
2.下面是ioc反转控制的xml文件
3. 下面是maven里面创建的测试类
packagecom.mars.springtest;import static org.junit.Assert.*;importcom.mars.learnspring.Person;importorg.junit.Test;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;public classPersonTest {
@Testpublic voidtest() {
ApplicationContext ioc=new ClassPathXmlApplicationContext("conf/ioc.xml");
//注意,下面两句被注释掉了,目的就是用来看看无参构造方法何时被调用//Person bean=(Person) ioc.getBean("person01");//System.out.println(bean);
}
}
4.执行上面第3部的测试类。其结果如下
"C:\Program Files\Java\jdk1.8.0_221\bin\java.exe"...
Person类的无参构造方法...
Process finished with exit code0
5.由此可见类的构造方法是子spring容器启动就被调用了。
6.01ioc反转控制里面配置多少个bean就会创建多少个相应的对象
6.02 同一个bean被调用两次,但这个bean对于的对象只会创建一个。
如下代码,我们调用了两次person01这个bean,但是它创建的对象却还是一个而不是两个,所以system.out里面输出结果为true。
@Testpublic voidtest() {
ApplicationContext ioc=new ClassPathXmlApplicationContext("conf/ioc.xml");
Person bean1=(Person) ioc.getBean("person01");
Person bean2=(Person) ioc.getBean("person01");
System.out.println(bean1==bean2);
}
输出结果
Person类的无参构造方法...
Person类的无参构造方法...trueProcess finished with exit code0