IOC操作Bean管理XML方式(注入空值和特殊符号)
目录
IOC操作Bean管理XML方式(注入空值和特殊符号)
(1)通过null标签注入空值:
标签注入空值
(2)属性值中包含特殊符号:
方法1:直接把“<”“>”进行转义 < >
方法2:把带特殊符号内容写到CDATA
先说一个概念,什么是字面量:
简单来说:字面量是指双引号引住的一系列字符,双引号中可以没有字符,可以只有一个字符,也可以有很多个字符。
例如:
提出问题:
有时候我们的属性值并不是全部都是有数据的,有些是空的值,那么这个时候我们怎么注入空的值的属性呢?
通过实际例子演示:
在Book图书类中进行修改:
我们现在需要写多一个address地址属性,假设这个属性的值我们需要设为空
package com.lbj.spring5;/*** 演示使用set方法进行注入属性*/
public class Book {//在类中创建属性:往book类中写入一个属性private String bname;//写入一个地址属性,假设这个属性的注入是空的值private String address;//创建属性对应的set方法:set方法注入属性public void setBname(String bname) {this.bname = bname;}//创建属性对应的set方法:set方法注入属性public void setAddress(String address) {this.address = address;}public void testBook(){System.out.println(bname+"::"+address);}
}
(1)通过null标签注入空值:
<null/>标签注入空值
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.xsd"><!--配置Book对象创建-->
<bean id="book" class="com.lbj.spring5.Book" ><!--使用property完成属性注入name:类里面的属性名称value:向属性注入的值--><property name="bname" value="红楼梦"></property><!--<null/>标签注入空值--><property name="address"><null/></property></bean></beans>
测试结果:
(2)属性值中包含特殊符号:
方法1:直接把“<”“>”进行转义 < >
方法2:把带特殊符号内容写到CDATA
CDATA表达式是 xml 配置文件相比较于其他配置文件的一个特别优秀的功能,不是 Spring 的功能
方法2的示例:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--配置Book对象创建-->
<bean id="book" class="com.lbj.spring5.Book" ><!--使用property完成属性注入name:类里面的属性名称value:向属性注入的值--><property name="bname" value="红楼梦"></property><property name="address"><value><![CDATA[<北京>]]></value></property>
</bean></beans>
测试结果: