可以通过 xml 配置的方式, 让 Spring 帮我们创建对象的时候注入一个 null

    Student.java

    1. package com.ctguyxr.spring5.entity;
    2. /**
    3. * Created by Intellij IDEA 2021.3
    4. * @author: Xinrui Yu
    5. * @date: 2021/12/9 10:25
    6. */
    7. public class Student {
    8. private Integer id;
    9. private String name;
    10. private String gender;
    11. public Student() {
    12. }
    13. public Student(Integer id, String name, String gender) {
    14. this.id = id;
    15. this.name = name;
    16. this.gender = gender;
    17. }
    18. public Integer getId() {
    19. return id;
    20. }
    21. public void setId(Integer id) {
    22. this.id = id;
    23. }
    24. public String getName() {
    25. return name;
    26. }
    27. public void setName(String name) {
    28. this.name = name;
    29. }
    30. public String getGender() {
    31. return gender;
    32. }
    33. public void setGender(String gender) {
    34. this.gender = gender;
    35. }
    36. @Override
    37. public String toString() {
    38. return "Student{" +
    39. "id=" + id +
    40. ", name='" + name + '\'' +
    41. ", gender='" + gender + '\'' +
    42. '}';
    43. }
    44. }

    xml配置

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    5. <bean id="student" class="com.ctguyxr.spring5.entity.Student">
    6. <property name="id" value="1" />
    7. <property name="name" value="yxr" />
    8. <property name="gender">
    9. <!--null标签用来配置属性的null值-->
    10. <null/>
    11. </property>
    12. </bean>
    13. </beans>

    测试

    1. @Test
    2. public void test2(){
    3. ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
    4. Student student = context.getBean("student", Student.class);
    5. System.out.println(student);
    6. }

    image.png