Spring安全性:获取NoSuchBean Exception错误

时间:2017-07-16 16:07:34

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

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

以下是我的应用程序与Spring-Security一起使用的片段。

弹簧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:错误   使用名称&#39; org.springframework.security.filterChains&#39;创建bean:   无法解析对bean的引用   &#39; org.springframework.security.web.DefaultSecurityFilterChain#0&#39; &#39; org.springframework.security.authentication.dao.DaoAuthenticationProvider#0&#39 ;:   无法解析对bean&user.detailsS​​ervice&#39;的引用在设置   bean属性&#39; userDetailsS​​ervice&#39 ;;嵌套异常是   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   bean命名为&#39; userDetailsS​​ervice&#39;已定义

我可能会遗漏一些xml配置。但经过这么多尝试才弄明白,我发现很难。请帮帮我。

2 个答案:

答案 0 :(得分:1)

修改:


OpenSSH_7.2p2 Ubuntu-4ubuntu2.2, OpenSSL 1.0.2g  1 Mar 2016 debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for * 
debug1: Connecting to xxx.xx.xxx.xxx [xxx.xx.xxx.xxx] port 22.
debug1: Connection established. 
debug1: permanently_set_uid: 0/0
debug1: identity file /home/whj/.ssh/whjwebsite type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/whj/.ssh/whjwebsite-cert type -1 
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1 debug1: match: OpenSSH_6.6.1 pat OpenSSH_6.6.1* compat 0x04000000
debug1: Authenticating to xxx.xx.xxx.xxx:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none 
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none 
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:aC1Ydp+6x8IP+TV5jEl7WwqW6sEycbznbfL09qON/OA
debug1: Host 'xxx.xx.xxx.xxx' is known and matches the ECDSA host key.
debug1: Found key in /root/.ssh/known_hosts:1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-debug1: Next authentication method: gssapi-keyex
debug1: No valid Key exchange context
debug1: Next authentication method: gssapi-with-mic
debug1: Unspecified GSS failure.  Minor code may provide more information No Kerberos credentials available
debug1: Unspecified GSS failure.  Minor code may provide more information No Kerberos credentials available
debug1: Unspecified GSS failure.  Minor code may provide more information debug1: Unspecified GSS failure.  Minor code may provide more information No Kerberos credentials available
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/whj/.ssh/whjwebsite
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-debug1: No more authentication methods to try. Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

要:

<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>

答案 1 :(得分:-1)

您需要在servlet-context.xml

中添加以下代码
<context:component-scan base-package="com.sparkle" />
<mvc:annotation-driven />

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