当bean的id在spring的bean.xml中设置为空时出现奇怪的异常

时间:2018-02-21 01:06:25

标签: java xml spring javabeans spring-config

只是出于好奇,我把bean里面的bean的id留空了。我期待异常类似" bean id未定义"或者" bean id不能为空" 但实际上,我得到了以下异常 -

cvc-datatype-valid.1.2.1: '' is not a valid value for 'NCName'.

它表示什么?

完全例外是 -

06:26:18.262 [main] DEBUG org.springframework.beans.factory.xml.PluggableSchemaResolver - Found XML schema [http://www.springframework.org/schema/beans/spring-beans-3.0.xsd] in classpath: org/springframework/beans/factory/xml/spring-beans-3.0.xsd
Exception in thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 13 in XML document from class path resource [beans.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 13; columnNumber: 94; cvc-datatype-valid.1.2.1: '' is not a valid value for 'NCName'.
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:399)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)

bean.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-3.0.xsd">

   <bean id = "employee" class = "com.test.springboot.spring_boot_example.Employee" >
      <property name = "name" value = "Arvind"/>
       <property name = "address" ref = "address"/>
   </bean>

   <bean id = "" class = "com.test.springboot.spring_boot_example.Address" scope="prototype">
      <property name = "houseNumber" value = "64"/>

   </bean>



</beans>

1 个答案:

答案 0 :(得分:2)

这是因为xml不会对DTD进行验证

由于id属性应该是NCName,因此xml解析器将抛出异常。 NCName不允许为空。

还有一个很好的q / a here来阅读有关它如何使用的更多信息