Spring IOC创建对象的方式
1. IOC创建对象方式
1.1 通过无参构造来创建
1、User.java
public class User {
private String name;
public User() {
System.out.println("user无参构造方法");
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("name="+ name );
}
}
2、beans.xml
<?xml version="1.0" encoding="UTF-8"?>
3、测试类
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//在执行getBean的时候, user已经创建好了 , 通过无参构造
User user = (User) context.getBean("user");
//调用对象的方法 .
user.show();
}
- 结果可以发现,在调用show方法之前,User对象已经通过无参构造初始化了!
1.2 通过有参构造方法来创建
将无参构造更改为有参构造
public UserT(String name) {
this.name = name;
}
2、beans.xml 有三种方式编写
3、测试
@Test
public void testT(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserT user = (UserT) context.getBean("userT");
user.show();
}
- 结论:在配置文件加载的时候。其中管理的对象都已经初始化了!