- 引入maven依赖
- 准备 JavaBean
- 编写Spring配置文件
- 编写测试类
准备 JavaBeanorg.springframework spring-context 5.3.22
package com.lihaozhe.ioc.dto;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 740885412941761394L;
private long id;
private String nickname;
private int gender;
public User() {
System.out.println("无参构造");
}
public User(long id, String nickname) {
this.id = id;
this.nickname = nickname;
System.out.println("id nickname 有参构造");
}
public User(long id, String nickname, int gender) {
this.id = id;
this.nickname = nickname;
this.gender = gender;
System.out.println("id nickname gender 有参构造");
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", nickname='" + nickname + ''' +
", gender=" + gender +
'}';
}
}
编写Spring配置文件
src/main/resouces/ioc/bean.xml
编写测试类
package com.lihaozhe.ioc;
import com.lihaozhe.ioc.dto.User;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class IocTest {
@Test
public void test01(){
// 获取 IOC 容器
ApplicationContext context = new ClassPathXmlApplicationContext("ioc/bean.xml");
// 从 IOC 容器中获取 JavaBean对象
User user01 = (User) context.getBean("user01");
User user02 = (User) context.getBean("user02");
System.out.println(user02);
System.out.println(user01 == user02);
}
@Test
public void test02(){
// 获取 IOC 容器
ApplicationContext context = new ClassPathXmlApplicationContext("ioc/bean.xml");
// 从 IOC 容器中获取 JavaBean对象
User user = (User) context.getBean("user03");
System.out.println(user);
}
@Test
public void test03(){
// 获取 IOC 容器
ApplicationContext context = new ClassPathXmlApplicationContext("ioc/bean.xml");
// 从 IOC 容器中获取 JavaBean对象
User user = (User) context.getBean("user04");
System.out.println(user);
}
}



