Соответствующий шаблон является строгим, но для контекста элемента не найдено объявления: компонент-сканирование
Я получаю следующие ошибки при попытке мой первый весенний проект:
Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'context:component-scan
Вот applicationContext.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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:component-scan base-package="com.xyz" />
</beans>
Что является причиной ошибки?
Ответы
Ответ 1
Вы не указали расположение схемы пространства имен контекста, что является причиной этой конкретной ошибки:
<beans .....
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
Ответ 2
Этот путь расположения схемы неверен:
http://www.springframework.org/schema/beans
Правильный путь должен заканчиваться на /
:
http://www.springframework.org/schema/beans/
Ответ 3
У меня были проблемы с
Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'security:http'
и для меня мне пришлось добавить spring -security-config jar в путь к классам
http://docs.spring.io/spring-security/site/docs/3.1.x/reference/ns-config.html
EDIT:
Возможно, у вас есть правильная зависимость в вашей pom.
Но...
Если вы используете несколько зависимостей spring и собираете в одну банку, тогда META-INF/spring.schemas
, вероятно, будет перезаписан spring.schemas
другой из ваших зависимостей spring.
(Извлеките этот файл из собранной банки, и вы поймете)
Spring схемы - это просто куча строк, которые выглядят так:
http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler
http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd
Но если другая зависимость перезаписывает этот файл, тогда определение будет получено из http, а если у вас есть брандмауэр/прокси, он не сможет его получить.
Одним из решений является добавление spring.schemas и spring.handlers в один файл.
Check:
Идея избежать того, что spring.handlers/spring.schemas будут перезаписаны при объединении нескольких зависимостей spring в одной банке
Ответ 4
Эта ошибка также может быть вызвана, если файл jar, содержащий требуемый XSD, не включен в ваш путь к развернутому классу.
Убедитесь, что зависимости доступны в вашем контейнере.
Ответ 5
Если вы используете STS, вы можете в Eclipse пометить файл конфигурации как "Bean Конфигурация" (вы можете указать, что при создании или по щелчку правой кнопкой мыши по XML файлу):
![Spring Инструменты > Добавить как Bean Конфигурация]()
У проекта должен быть Spring Nature (правый клик по проекту maven):
![Spring Инструменты > Добавить Spring Природа проектa]()
затем spring.xml
открывается по умолчанию с помощью Spring Config Editor
![Открыть с помощью > Spring Редактор конфигурации]()
и этот редактор имеет вкладку Пространства имен
![Spring Редактор конфигурации - вкладка Пространства имен]()
Позволяет указать пространства имен:
![Spring Редактор конфигурации - пример пространства имен]()
Имейте в виду, что это зависит от зависимостей (с использованием проекта maven), поэтому, если spring-tx
не определен в maven pom.xml, опция отсутствует, что предотвращает Подстановочный шаблон является строгим, но объявления для элемента 'tx: annotation-driven' context: component-scan ' не найдены...
Ответ 6
Это слишком поздно, но несколько может быть полезным для других.
Соответствующий шаблон является строгим, но объявления не могут быть найдены для элемент ": компонент-сканирование
который означает, что у вас есть Пропущенные объявления или обязательные объявления Не найдено в вашем XML
В моем случае я забыл добавить следующее
После добавления этой проблемы ушел Прочь
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
Ответ 7
когда вы добавляете контекст: компонент-сканирование в первый раз в xml, необходимо добавить следующее.
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
Ответ 8
Правильный путь не должен заканчиваться на "/", я ошибся, что вызвало проблему
Правильно:
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
Ответ 9
С помощью объявления пространства имен и расположения схемы вы также можете проверить синтаксис использования пространства имен, например: -
<beans xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation= http://www.springframework.org/'enter code here'schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-driven/> <!-- This is wrong -->
<context:annotation-config/> <!-- This should work -->
Ответ 10
Добавьте контекст xmlns с http, как показано ниже
xmlns:context="http://www.springframework.org/schema/context"
Ответ 11
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
Приведенные выше ссылки должны быть включены
<context:property-placeholder location="classpath:sport.properties" />
<bean id="myFortune" class="com.kiran.springdemo.HappyFortuneService"></bean>
<bean id="myCoach" class="com.kiran.springdemo.setterinjection.MyCricketCoach">
<property name="fortuner" ref="myFortune" />
<property name="emailAddress" value="${ipl.email}" />
<property name="team" value="${ipl.team}" />
</bean>
</beans>
Ответ 12
Добавьте это две схемы схемы. Этого достаточно и эффективно вместо добавления всей ненужной схемы
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd