spring set注入-null和空字符串
举例说明:
Cat类
public class Cat {
private String name;
private int age;
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
配置文件set-di.xml
<bean id="catBean" class="per.sxhzs.spring6.bean.Cat">
<!--不给属性注入,属性的默认值就是null-->
<!--<property name="name" value="hxh"/>-->
<!--这不是注入null,这只是注入了一个“null“字符串-->
<!--<property name="name" value="null"/>-->
<!--这种方式是手动注入null-->
<!--<property name="name">
<null/>
</property>-->
<!--注入空字符串第一种方式-->
<!--<property name="name" value=""/>-->
<!--注入空字符串第二种方式-->
<property name="name">
<value/>
</property>
<property name="age" value="20"/>
</bean>
测试类
@Test
public void testNull() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("set-di.xml");
Cat catBean = applicationContext.getBean("catBean", Cat.class);
System.out.println(catBean);
}
@Test
public void testNull() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("set-di.xml");
Cat catBean = applicationContext.getBean("catBean", Cat.class);
System.out.println(catBean.getName());
}
运行结果



浙公网安备 33010602011771号