需要顯式將 Bean 屬性設置為 null,而非不注入(保持默認值)或注入字符串 "null"。
public class MemberBean {
public String name;
public Member member; // 自定義類型
public void setName(String name) { this.name = name; }
public void setMember(Member member) { this.member = member; }
}
public class Member { } // 空類
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="memberBean" class="www.csdn.spring.constructor.bean.MemberBean">
<!-- 注入 null 值,而非字符串 "null" -->
<property name="name">
<null/>
</property>
<property name="member">
<null/>
</property>
</bean>
</beans>
public class MemberTest {
@Test
public void testBean() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-null.xml");
MemberBean bean = context.getBean("memberBean", MemberBean.class);
System.out.println(bean.name); // 輸出: null
System.out.println(bean.member); // 輸出: null
}
}
| 配置 | 效果 |
|---|---|
<property name="x"><null/></property> | 屬性 x = null (Java null) |
<property name="x" value="null"/> | 屬性 x = "null" (字符串) |
| 無 property 元素 | 屬性保持默認值 (基本類型 0/false,引用類型 null) |