通配符的匹配很全面, 但无法找到元素 XXXXX' 的声明

问题配置Spring的时候容易发生如题的这样一个经常性的错误,错误如下(以context为例)

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: 
Line 8 in XML document from class path resource [applicationContext.xml] is invalid; 
nested exception is org.xml.sax.SAXParseException; 
lineNumber: 8; columnNumber: 47; cvc-complex-type.2.4.c: 
通配符的匹配很全面, 但无法找到元素 'context:component-scan' 的声明。

再看看beans的约束:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    >

咦?这不是有context的声明吗,

没错,不过还少了一些东西,那就是关于context的xsi的模式地址 xsi:schemaLocation 的更新

  1. xmlns:全名是xml namespace,也即是为当前的这个xml指定命名空间。

  2. xmlns:xsi:是指当前xml所要遵循的标签规范.

  3. 如上xmlns配上hdp, xsi, aop, cache, context, mvc…都是当前xml要使用到的一个标签,后面就是指定标签所要遵循的规范。

  4. xsi:schemaLocation:指定的命名空间对应的验证文件,用来定义xml schema的地址,也就是xml书写时需要遵循的语法,用于声明了目标命名空间的模式文档。。两部分组成,前面部分就是命名空间的名字,后面是xsd(xmlschema)文档的地址,也是就表示把定义这个命名空间的schema文件给引用进来,好让eclipse这类型工具能够解析和验证你的xml文件是否符合语法规范。简单来说就是声明了目标命名空间的模式文档

解决方案:除了要添加xmlns:XXX之外,还需要添加对应的xsi:schemaLocation【可以去google一下所需要的xsi:schemaLocation

如下:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context.xsd"
    >

猜你喜欢

转载自www.cnblogs.com/Xieyang-blog/p/8972201.html
今日推荐