在XML配置中"<",">","&"等特殊字符是不能直接保存的,否则XML语法检查时就会报错,可以通过以下两种方式讲包含特殊符号的属性注入到Bean中.
1.转义
在XML中,特殊符号必须进行转义才能保存进XML配置中,例如"<",">","&"等.
在XML中,需要转义的字符如下表所示:
特殊字符 | 转义字符 |
---|---|
& | & |
< | < |
> | > |
" | " |
' | ' |
注意:在转义过程中,
(1).转义序列字符之间不能有空格;
(2).转义序列必须一";"结束;
(3).独立出现的"&"不会被认为是转义的开始;
(4).区分大小写.
示例
导入的依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.20</version>
</dependency>
</dependencies>
package com.demo.pojo;
public class Example {
private String name;
private int age;
private String sex;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Example{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
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">
<bean id="example" class="com.demo.pojo.Example">
<property name="name" value="<测试>"/>
<property name="age" value="1"/>
<property name="sex" value=""男""/>
</bean>
</beans>
package com.demo.pojo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("application.xml");
Example example = context.getBean("example", Example.class);
System.out.println(example.toString());
}
}
执行结果
2.使用短字符串<![CDATA[]]>
通过短字符串<!CDATA[]>将包含特殊符号的属性值包裹起来,可以让xml解析器忽略对其中内容的解析,以属性原本的样子注入到Bean中.
注意:
(1).此部分不能再包含"]]>";
(2).不允许嵌套使用;
(3)."]]>"中不能包含空格或者换行.
示例
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">
<bean id="example" class="com.demo.pojo.Example">
<property name="name">
<null/>
</property>
<property name="age" value="1"/>
<property name="sex">
<value><![CDATA[<女>]]></value>
</property>
</bean>
</beans>
结果