Невозможно найти Spring NamespaceHandler для пространства имен схемы XML [http://www.springframework.org/schema/security] - PullRequest
54 голосов
/ 25 августа 2011

Я разрабатываю свое первое приложение в весенней безопасности. Мой файл applicationContext-security.xml выглядит так:

<?xml version="1.0" encoding="UTF-8"?>

<!--
  -  Namespace-based OpenID configuration
  -->

<b:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:b="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
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <http>
        <intercept-url pattern="/**" access="ROLE_USER"/>
        <intercept-url pattern="/index.xhtml*" filters="none"/>
        <logout/>
        <openid-login login-page="/index.xhtml" authentication-failure-url="/index.xhtml?login_error=true">
            <attribute-exchange>
                <openid-attribute name="email" type="http://schema.openid.net/contact/email" required="true" count="2"/>
                <openid-attribute name="name" type="http://schema.openid.net/namePerson/friendly" />
            </attribute-exchange>
        </openid-login>
        <remember-me token-repository-ref="tokenRepo"/>
    </http>

    <b:bean id="tokenRepo"
            class="org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl" />

    <authentication-manager alias="authenticationManager"/>

    <user-service id="userService">
        <user name="http://user.myopenid.com/" authorities="ROLE_SUPERVISOR,ROLE_USER" />
    </user-service>

</b:beans>

и файл Web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

    <display-name>Spring Security OpenID Demo Application</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext-security.xml
        </param-value>
    </context-param>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/classes/log4j.properties</param-value>
    </context-param>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>openid.root</param-value>
    </context-param>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
      <filter-name>springSecurityFilterChain</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
     <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

Очистка и сборка приложения прошла успешно, но при попытке развернуть приложение jetty 7 выдает мне следующую ошибку:

SEVERE: сбой инициализации контекста
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: проблема конфигурации: не удается найти Spring NamespaceHandler для пространства имен схемы XML [http://www.springframework.org/schema/security]
Ресурс-нарушитель: ресурс ServletContext [/WEB-INF/applicationContext-security.xml]
в org.springframework.beans.factory.parsing.FailFastProblemReporter.error (FailFastProblemReporter.java:68)
в org.springframework.beans.factory.parsing.ReaderContext.error (ReaderContext.java:85)
в org.springframework.beans.factory.parsing.ReaderContext.error (ReaderContext.java:80)

Пробовал все, но не могу решить эту ошибку. Любая помощь будет оценена.

EDIT Я попытался добавить 3.0.2 версию Spring-Security и получил это:

Сбой инициализации контекста
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: строка 13 в XML-документе из ресурса ServletContext [/WEB-INF/applicationContext-security.xml] недопустима;
вложенным исключением является org.xml.sax.SAXParseException; номер строки: 13; номер столбца: 11; cvc-complex-type.2.4.c: соответствующий шаблон является строгим, но не найдено никакого объявления для элемента 'http'. в org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions (XmlBeanDefinitionReader.java:396)
в org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions (XmlBeanDefinitionReader.java:334

Ответы [ 3 ]

89 голосов
/ 25 августа 2011

Вам нужен spring-security-config.jar на вашем пути к классам.

Исключение означает, что пространство имен security: xml не может быть обработано пружинными "анализаторами".Они являются реализациями интерфейса NamespaceHandler, поэтому вам нужен обработчик, который знает, как обрабатывать теги <security:.Это SecurityNamespaceHandler находится в spring-security-config

7 голосов
/ 15 сентября 2012

У меня была такая же проблема.Единственное, что решило это, - это слияние содержимого META-INF / spring.handler и META-INF / spring.schemas каждого файла JAR Spring в одни и те же имена файлов в рамках моего проекта META-INF.

Эти двапотоки объясняют это лучше:

0 голосов
/ 06 апреля 2016

В моем случае это было вызвано пользовательскими записями манифеста, добавленными maven-jar-plugin.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <archive>
            <index>true</index>
            <manifest>
                <addClasspath>true</addClasspath>
            </manifest>
            <manifestEntries>
                <git>${buildNumber}</git>
                <build-time>${timestamp}</build-time>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>

Удаление следующих записей устранило проблему

<index>true</index>
<manifest>
    <addClasspath>true</addClasspath>
</manifest>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...