文章目录
1、IOC创建对象方式
1.1.通过无参构造方法来创建
- User.java
public class User {
private String name;
public User(){
System.out.println("User的无参构造");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("name:"+name);
}
}
- applicationContext.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="user" class="com.xxc.pojo.User">
<property name="name" value="江南"/>
</bean>
</beans>
- 测试
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) context.getBean("user");
user.show();
}
}
说明:结果可以发现,在调用show方法之前,User对象已经通过无参构造初始化了。
1.2.通过有参构造方法来创建
- userT.java
public class UserT {
private String name;
public UserT(){
System.out.println("UserT的无参构造");
}
public UserT(String name){
this.name = name;
System.out.println("UserT的有参构造");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("name:"+name);
}
}
- applicationContext.xml有三种方法
<!-- 第一种根据index参数下标设置 -->
<bean id="userT" class="com.xxc.pojo.UserT">
<!-- index指构造方法 , 下标从0开始 -->
<constructor-arg index="0" value="江南1"/>
</bean>
<!-- 第二种根据参数类型设置 -->
<bean id="userT" class="com.xxc.pojo.UserT">
<constructor-arg type="java.lang.String" value="江南2"/>
</bean>
<!-- 第三种根据参数名字设置 -->
<bean id="userT" class="com.xxc.pojo.UserT">
<!-- name指参数名 -->
<constructor-arg name="name" value="江南3"/>
</bean>
- 测试
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserT user = (UserT) context.getBean("userT");
user.show();
}
}
结论:这里对于无参构造的user一直存在,说明在配置文件加载的时候。其中管理的对象都已经初始化了!就好比spring是一个婚介所,只要注册,那么信息就在婚介所中了,别人想看,只需要调取就可以。