1.创建maven工程
2.添加Spring依赖
在maven项目的pom.xml文件中添加一下代码
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.18</version>
</dependency>
3.创建Spring配置文件
在Resources目录下创建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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
4.创建实体类
public class Student {
private String id;
private String name;
private String sex;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
5.配置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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--将指定类配置给Spring,创建Bean实例-->
<bean id="student" class="com.gyh.ioc.pojo.Student"></bean>
</beans>
6.测试
public class Test {
public static void main(String[] args) {
//初始化Spring容器并加载配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//通过getBean方法获取指定的Bean,获取之后需要进行强制类型转换
Student student = (Student) context.getBean("student");
System.out.println(student);
}
}
运行结果:
这里可以看到,我们没有使用new关键字来创建对象,而是通过Spring成功获取了Student的实现类对象,这就是SpringIoC容器的工作机制。
通过配置文件给对象的属性赋值
<bean id="student" class="com.gyh.ioc.pojo.Student">
<property name="id" value="1001"/>
<property name="name" value="Spring"/>
<property name="sex" value="男"/>
<property name="age" value="18"/>
</bean>
- 运行结果
因此我们不仅可以通过配置文件创建实现类的对象,还可以给对象的属性赋值。