前端之家收集整理的这篇文章主要介绍了
依赖注入null空值,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
其实注入null空值很简单,但偏偏总有人写不对,下面写一个简单的小实例
实体类:
public class PersonServiceBean {
private String name;
private String sex;
private Integer age;
private Date birth;
public PersonServiceBean() {
super();
// TODO Auto-generated constructor stub
System.out.println("构造器初始化对象");
}
public PersonServiceBean(String name,String sex,Integer age,Date birth) {
super();
this.name = name;
this.sex = sex;
this.age = age;
this.birth = birth;
}
public void setName(String name) {
System.out.println("name的set方法------------"+name);
this.name = name;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setAge(Integer age) {
this.age = age;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "PersonServiceBean [name=" + name + ",sex=" + sex + ",age="
+ age + ",birth=" + birth + "]";
}
}
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-2.5.xsd">
<bean id="personServiceBean" class="cn.csdn.hr.service.PersonServiceBean">
<property name="birth">
<null></null>
</property>
</bean>
</beans>
这样就可以了,但是偏偏有人总是在<property name="birth">
中加上一个value=”null”,就是想不起来有一个null标签,要说的是如果不写<property name="XXX"></property>,注入的也会是空值哟
测试方法
@Test
public void test() {
//第一步:获取应用程序上下文对象
ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:beanNull.xml");
//第二步:根据应用程序上下文对象的getBean(id名称)方法获取实例bean对象
PersonServiceBean p=(PersonServiceBean) ac.getBean("personServiceBean");
System.out.println(p.toString());
}
结果:
构造器初始化对象
PersonServiceBean [name=null,sex=null,age=null,birth=null]
原文链接:https://www.f2er.com/javaschema/286826.html