可以通过 xml 配置的方式, 让 Spring 帮我们创建对象的时候注入一个 null
值
Student.java
package com.ctguyxr.spring5.entity;
/**
* Created by Intellij IDEA 2021.3
* @author: Xinrui Yu
* @date: 2021/12/9 10:25
*/
public class Student {
private Integer id;
private String name;
private String gender;
public Student() {
}
public Student(Integer id, String name, String gender) {
this.id = id;
this.name = name;
this.gender = gender;
}
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 String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
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="student" class="com.ctguyxr.spring5.entity.Student">
<property name="id" value="1" />
<property name="name" value="yxr" />
<property name="gender">
<!--null标签用来配置属性的null值-->
<null/>
</property>
</bean>
</beans>
测试
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
Student student = context.getBean("student", Student.class);
System.out.println(student);
}