Spring-IOC-基于XML的DI-注入字面量属性
1、创建Person类
package com.orz.spring.bean;
/**
* @author orz
* @create 2020-10-18 15:55
*/
public class Person {
private String name;
private String gender;
private Integer age;
public Person() {
}
public Person(String name, String gender, Integer age) {
this.name = name;
this.gender = gender;
this.age = age;
}
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;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
'}';
}
}
2、注入null值
错误写法:
<bean id="person" class="com.orz.spring.bean.Person">
<property name="name" value="null"/>
<property name="age" value="23"/>
<property name="gender" value="男"/>
</bean>
@Test
public void test1()
{
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
Person person = applicationContext.getBean("person", Person.class);
System.out.println(person.getName() == null);
}
false
正确写法:
<bean id="person" class="com.orz.spring.bean.Person">
<property name="name">
<null/>
</property>
<property name="age" value="23"/>
<property name="gender" value="男"/>
</bean>
@Test
public void test1()
{
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
Person person = applicationContext.getBean("person", Person.class);
System.out.println(person.getName() == null);
}
true
3、特殊字符
如:name=<<李华>>
方式一:使用 标签的 <![CDATA[ ]]>
<bean id="person" class="com.orz.spring.bean.Person">
<property name="name">
<value><![CDATA[<<李华>>]]></value>
</property>
<property name="age" value="23"/>
<property name="gender" value="男"/>
</bean>
@Test
public void test1()
{
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
Person person = applicationContext.getBean("person", Person.class);
System.out.println(person);
}
Person{name='<<李华>>', gender='男', age=23}
方式二、使用xml转义字符
显示结果 描述 转义字符 十进制
空格  
< 小于号 < <
> 大于号 > >
& 与号 & &
" 双引号 " "
' 单引号 ' '
× 乘号 × ×
÷ 除号 &divde; ÷
<bean id="person" class="com.orz.spring.bean.Person">
<property name="name" value="<<李华>>"/>
<property name="age" value="23"/>
<property name="gender" value="男"/>
</bean>
@Test
public void test1()
{
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
Person person = applicationContext.getBean("person", Person.class);
System.out.println(person);
}
}
Person{name='<<李华>>', gender='男', age=23}