【问题标题】:Spring security : Getting NoSuchBean Exception errorSpring 安全性:获取 NoSuchBean 异常错误
【发布时间】:2017-12-21 04:33:35
【问题描述】:

我是 Spring 安全的新手,我正在使用 Spring 安全 4 开发 Spring 4。我已经按照一个教程开始,但每次我收到错误 NoSuchBeanDefinition found。 不知何故,我已经尝试了网络和 stackoverflow 上提到的所有建议,但无法弄清楚。

以下是我的应用程序的 sn-ps 以使用 Spring-Security。

spring-security.xml

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

<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />

    <!-- access denied page -->
    <access-denied-handler error-page="/403" />
    <form-login 
        login-page="/login" 
        default-target-url="/welcome"
        authentication-failure-url="/login?error" 
        username-parameter="username"
        password-parameter="password" />
    <logout logout-success-url="/login?logout" />
    <!-- enable csrf protection -->
    <csrf />
</http>

<authentication-manager>
    <authentication-provider user-service-ref="userDetailsService" >
        <password-encoder hash="bcrypt" />    
    </authentication-provider>
</authentication-manager>

</beans:beans>


Web.xml

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

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

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Processes application requests -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml, /WEB-INF/spring/appServlet/spring-security.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>


<!-- Spring Security -->
<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>


<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

 <session-config>
    <tracking-mode>COOKIE</tracking-mode>
 </session-config>


servlet-context.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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

<!--  Testing Database MySQL Local System -->        
<beans:bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"  />
    <beans:property name="url" value="jdbc:mysql://127.0.0.1:3306/tutorzest" />
    <beans:property name="username" value="root" />
    <beans:property name="password" value="root" />
</beans:bean>  


<!-- Hibernate 4 SessionFactory Bean definition --> 
<beans:bean id="hibernate4AnnotatedSessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <beans:property name="dataSource" ref="dataSource" />
    <beans:property name="annotatedClasses">
        <beans:list>
            <beans:value>com.spring.model.User</beans:value>
            <beans:value>com.spring.model.UserRole</beans:value>
        </beans:list>
    </beans:property>
    <beans:property name="hibernateProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
            </beans:prop>
            <beans:prop key="hibernate.show_sql">true</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>

<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>


<beans:bean id="userDao" class="com.spring.dao.UserDaoImpl">
    <beans:property name="sessionFactory"   ref ="hibernate4AnnotatedSessionFactory"/>
</beans:bean>

<beans:bean id="userDetailsService" class="com.spring.service.MyUserDetailsService">
</beans:bean>

<context:component-scan base-package="com.spring.controller" /> 
<tx:annotation-driven transaction-manager="transactionManager"/>

 </beans:beans>

** MyUserDetailsS​​ervice**

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

//get user from the database, via Hibernate
@Autowired
private UserDao userDao;

@Transactional(readOnly=true)
@Override
public UserDetails loadUserByUsername(final String username)
    throws UsernameNotFoundException {

    com.xpedia.spring.model.User user = userDao.findByUserName(username);
    List<GrantedAuthority> authorities =
                                  buildUserAuthority(user.getUserRole());

    return buildUserForAuthentication(user, authorities);

}

// Converts com.mkyong.users.model.User user to
// org.springframework.security.core.userdetails.User
private User buildUserForAuthentication(com.xpedia.spring.model.User user,
    List<GrantedAuthority> authorities) {
    return new User(user.getUsername(), user.getPassword(),
        user.isEnabled(), true, true, true, authorities);
}

private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles)  

    Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

    // Build user's authorities
    for (UserRole userRole : userRoles) {
        setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
    }

    List<GrantedAuthority> Result = 
    new ArrayList <GrantedAuthority>    (setAuths);

    return Result;
}

}


执行后出现以下错误:

org.springframework.beans.factory.BeanCreationException: 错误 创建名为“org.springframework.security.filterChains”的bean: 无法解析对 bean 的引用 'org.springframework.security.web.DefaultSecurityFilterChain#0' 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0': 设置时无法解析对 bean 'userDetailsS​​ervice' 的引用 bean 属性 'userDetailsS​​ervice';嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 定义了名为“userDetailsS​​ervice”的 bean

我可能缺少一些 xml 配置。但是经过这么多尝试弄清楚后,我发现它很困难。请帮我解决这个问题。

【问题讨论】:

  • 您的安全配置是根应用程序上下文,而另一个是子上下文。您正在从根/父上下文中的子上下文引用 UserSetailService。孩子可以引用父上下文 bean,但它不能以其他方式工作。解决此问题的一种方法是仅在您的 servlet 上下文中扫描控制器,并在根上下文中扫描除控制器之外的所有内容。
  • 同时从 Dispatcher Servlet 初始化参数中删除安全上下文。

标签: java spring hibernate spring-mvc spring-security


【解决方案1】:

修改这个:

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

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Processes application requests -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml, /WEB-INF/spring/appServlet/spring-security.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

收件人:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/appServlet/servlet-context.xml
            /WEB-INF/spring/appServlet/spring-security.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

【讨论】:

  • 谢谢@Ivan .. 你的建议很有效,它对我前进有很大帮助。
【解决方案2】:

您需要在servlet-context.xml中添加波纹管代码

<context:component-scan base-package="com.sparkle" />
<mvc:annotation-driven />

<bean id="userDetailsService"
    class="com.spring.service.MyUserDetailsService">

【讨论】:

    猜你喜欢
    • 2015-09-13
    • 2013-09-27
    • 1970-01-01
    • 2013-08-21
    • 2012-07-07
    • 1970-01-01
    • 2019-12-28
    • 2019-02-27
    • 2014-02-25
    相关资源
    最近更新 更多