依赖注入就是对类的属性进行赋值
4.1、环境搭建
创建名为spring_ioc_xml的新module,过程参考3.1节
4.1.1、创建spring配置文件
<?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">
</beans>
4.1.2、创建学生类Student
package org.rain.spring.pojo;
/**
* @author liaojy
* @date 2023/7/27 - 22:33
*/
public class Student {
private Integer id;
private String name;
private Integer age;
private String sex;
public Student() {
}
public Student(Integer id, String name, Integer age, String sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
4.2、setter注入(常用)
4.2.1、配置bean
<!--
property标签:通过组件类的setXxx()方法给组件对象设置属性
name属性:指定属性名
value属性:设置属性值
-->
<bean id="student" class="org.rain.spring.pojo.Student">
<property name="id" value="0011"></property>
<property name="name" value="张三"></property>
<property name="age" value="23"></property>
<property name="sex" value="男"></property>
</bean>
4.2.2、测试
package org.rain.spring.test;
import org.junit.Test;
import org.rain.spring.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author liaojy
* @date 2023/7/27 - 22:43
*/
public class IOCByXmlTest {
@Test
public void testDISetter(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-ioc.xml");
Student student = applicationContext.getBean("student", Student.class);
System.out.println(student);
}
}
4.3、构造器注入
4.3.1、配置bean
注意:constructor-arg标签的数量,必须和某一个构造器方法的参数数量一致
<!--
constructor标签:通过组件类的有参构造方法给组件对象设置属性
name属性:指定有参构造方法参数名
value属性:设置有参构造方法参数值
-->
<bean id="studentTwo" class="org.rain.spring.pojo.Student">
<constructor-arg name="id" value="1002"></constructor-arg>
<constructor-arg name="name" value="李四"></constructor-arg>
<constructor-arg name="age" value="24"></constructor-arg>
<constructor-arg name="sex" value="女"></constructor-arg>
</bean>
4.3.2、测试
@Test
public void testDIConstructor(){
ApplicationContext appli