结论:Spring在创建spring容器的时候就创建的类的对象(调用了类的无参构造方法)
1. 下面我们创建一个Person类用于测试
package com.mars.learnspring; import com.sun.xml.internal.ws.addressing.WsaActionUtil; public class Person { private String name; private String gender; private Integer age; private String email; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "Person{" + "name=‘" + name + ‘\‘‘ + ", gender=‘" + gender + ‘\‘‘ + ", age=" + age + ", email=‘" + email + ‘\‘‘ + ‘}‘; }
//注意:下面的无参构造方法用于测试 public Person() { System.out.println("Person类的无参构造方法..."); } }
2.下面是ioc反转控制的xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="person01" class="com.mars.learnspring.Person"> <property name="name" value="黄晓明"></property> <property name="age" value="43"></property> <property name="gender" value="男"></property> <property name="email" value="huangxiaoming@javaspring.com"></property> </bean> </beans>
3. 下面是maven里面创建的测试类
package com.mars.springtest; import static org.junit.Assert.*; import com.mars.learnspring.Person; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class PersonTest { @Test public void test() { 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 code 0
5.由此可见类的构造方法是子spring容器启动就被调用了。
6.01ioc反转控制里面配置多少个bean就会创建多少个相应的对象
6.02 同一个bean被调用两次,但这个bean对于的对象只会创建一个。
如下代码,我们调用了两次person01这个bean,但是它创建的对象却还是一个而不是两个,所以system.out里面输出结果为true。
@Test public void test() { 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类的无参构造方法... true Process finished with exit code 0
原文:https://www.cnblogs.com/majestyking/p/12337312.html