Spring Security:无法在UserDetailsS​​ervice类中自动装配DAO

时间:2015-06-28 11:29:49

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

这个问题已被多次提出,我厌倦了许多解决方案,但失败了。

我正在尝试将用户映射到Spring Security用户。我的security.xml能够看到我的userDao类。我不明白为什么我不能自动上课。

我的spring-security.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:security="http://www.springframework.org/schema/security"
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.2.xsd
                http://www.springframework.org/schema/security 
                http://www.springframework.org/schema/security/spring-security-3.2.xsd
                http://www.springframework.org/schema/context 
                http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    <context:component-scan base-package="com.memorize" /> 
    <!-- This is where we configure Spring-Security  -->
    <security:http auto-config="true" use-expressions="true" access-denied-page="/memorize/auth/403"  >

    <security:intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />

    <security:form-login
        login-page="/memorize/auth/login"
        authentication-failure-url="/memorize/auth/login?error=true"
        default-target-url="/memorize/movie/sp"/>

    <security:logout
        invalidate-session="true"
        logout-success-url="/memorize/login"
        logout-url="/memorize/movie/sps"/>

    </security:http>

    <!-- Declare an authentication-manager to use a custom userDetailsService -->
    <security:authentication-manager>
        <security:authentication-provider user-service-ref="customUserDetailsService">
            <security:password-encoder ref="passwordEncoder"/>
        </security:authentication-provider>
    </security:authentication-manager>

    <!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database -->
    <bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>

</beans>

我正在使用此标记扫描我的所有组件:

 <context:component-scan base-package="com.memorize" /> 

这是我的springmvc-servlet.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:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"

xsi:schemaLocation="
                  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
                  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd    
                  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
                  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
                  http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
                  http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
                  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <tx:annotation-driven transaction-manager="txManager"/> 
    <context:component-scan base-package="com.memorize" />
    <mvc:annotation-driven />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/springdb" />
        <property name="username" value="xxx" />
        <property name="password" value="xxx" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingResources">
            <list>
                <value>/mappings/Users.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <bean id="txManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="persistenceExceptionTranslationPostProcessor"
        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <bean id="usersDAO" class="com.memorize.dao.impl.UsersDAOImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="customUserDetailsService" class="com.memorize.service.CustomUserDetailsService">
        <property name="usersDAO" ref="usersDAO" />
    </bean>

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>

这是我的CustomUserDetailsS​​ervice类

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UsersDAO usersDAO;

错误是这样的:

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.service.UsersService com.memorize.controller.UsersController.usersService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.dao.UsersDAO com.memorize.service.impl.UsersServiceImpl.usersDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.service.UsersService com.memorize.controller.UsersController.usersService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.dao.UsersDAO com.memorize.service.impl.UsersServiceImpl.usersDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 23 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usersServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.dao.UsersDAO com.memorize.service.impl.UsersServiceImpl.usersDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.memorize.dao.UsersDAO com.memorize.service.impl.UsersServiceImpl.usersDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 36 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.memorize.dao.UsersDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 38 more

我的UsersDao类

public interface UsersDAO {

    void saveOrUpdate(Users user);
    Users find(int userId);

}

我的用户DAOImpl是:

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.memorize.dao.UsersDAO;
import com.memorize.model.Users;

public class UsersDAOImpl implements UsersDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf){
        this.sessionFactory = sf;
    }

    public void save(Users u) {
        Session session = this.sessionFactory.getCurrentSession();
        session.persist(u);
    }

    @Override
    public void saveOrUpdate(Users user) {
        // TODO Auto-generated method stub
        Session session = this.sessionFactory.getCurrentSession();
        session.persist(user);
    }

    @Override
    public Users find(int id) {
        // TODO Auto-generated method stub
        Session session = this.sessionFactory.getCurrentSession();
        return (Users) session.get(Users.class, id);
    }
}

Web.xml中

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

<web-app id="WebApp_ID" version="2.4">

    <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>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
                
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/memorize/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

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

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

更新

建议之后,我改变了我的UsersDAOImpl:

我的用户DAOImpl是:

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.memorize.dao.UsersDAO;
import com.memorize.model.Users;

@Repository
public class UsersDAOImpl implements UsersDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sf){
        this.sessionFactory = sf;
    }

    public void save(Users u) {
        Session session = this.sessionFactory.getCurrentSession();
        session.persist(u);
    }

    @Override
    public void saveOrUpdate(Users user) {
        // TODO Auto-generated method stub
        Session session = this.sessionFactory.getCurrentSession();
        session.persist(user);
    }

    @Override
    public Users find(int id) {
        // TODO Auto-generated method stub
        Session session = this.sessionFactory.getCurrentSession();
        return (Users) session.get(Users.class, id);
    }
}

然而,在此更改后,我收到此错误:

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.memorize.dao.impl.UsersDAOImpl.sessionFactory;
No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. 
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}.

现在我无法在UsersDAOImpl类下自动连接我的sessionFactory。

3 个答案:

答案 0 :(得分:1)

@Repository实施添加UsersDAO注释,以便该类可以包含在组件扫描中

@Repository
public class UsersDAOImpl implements UsersDAO {

答案 1 :(得分:1)

你正在扫描com.memorize

  <context:component-scan base-package="com.memorize" /> 

但是只有带有@ controller,@ service,@ component,@ Repository等注释的类才会成为自动接线的候选者而其他类则不是。所以请考虑相应地注释你的类以进行正确的自动接线。

@Component - &gt;任何Spring管理的组件的通用构造型

<强> @Repository - &GT;持久层的构造型

@Service - &gt;服务层的构造型

@Controller - &gt;表示层的构造型(spring-mvc)

以下内容应解决错误。

@Repository
public class UsersDAOImpl implements UsersDAO {
 @Autowired
private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sf){
    this.sessionFactory = sf;
}

public void save(Users u) {
    Session session = this.sessionFactory.getCurrentSession();
    session.persist(u);
}

@Override
public void saveOrUpdate(Users user) {
    // TODO Auto-generated method stub
    Session session = this.sessionFactory.getCurrentSession();
    session.persist(user);
}

@Override
public Users find(int id) {
    // TODO Auto-generated method stub
    Session session = this.sessionFactory.getCurrentSession();
    return (Users) session.get(Users.class, id);
}

}

答案 2 :(得分:1)

我认为配置问题是UserDao bean如果在不同的上下文中定义(servlet的一个)。同样适用于SessionFactory,它不会被自动装配。我的建议是将公共bean移动到root-context,它被加载到servlet和securitie的上下文中。

一个例子:

<强>根context.xml中

在根上下文中我自动装配(通过组件扫描)每个非@Controller的bean

    <context:component-scan base-package="pl.com.suadeo.nwfm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="regex" expression="pl.com.suadeo.nwfm.webservice.*"/>
    </context:component-scan>

    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:properties/application.properties</value>
            </list>
        </property>
    </bean>

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="${dataSource.name}"/>
        <property name="packagesToScan" value="pl.com.suadeo.nwfm.models"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${sessionFactory.hibernate.dialect}</prop>
                <prop key="hibernate.hbm2ddl.auto">${sessionFactory.hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.show_sql">${sessionFactory.hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${sessionFactory.hibernate.format_sql}</prop>
                <prop key="hibernate.hbm2ddl.import_files">${sessionFactory.hibernate.import_files}</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="localeResolver"
          class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="pl"/>
    </bean>

    <!---->
    <!--MESSAGE SOURCE-->
    <!---->
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="basenames">
            <list>
                <value>/WEB-INF/message/labels</value>
                <value>/WEB-INF/message/form-errors</value>
                <value>/WEB-INF/message/messages</value>
            </list>
        </property>
        <property name="useCodeAsDefaultMessage" value="${messageSource.useCodeAsDefaultMessage}"/>
        <property name="fallbackToSystemLocale" value="true"/>
        <property name="cacheSeconds" value="${messageSource.cacheSeconds}"/>
    </bean>

</beans>

<强> servlet的context.xml中

在servlet上下文中,我正在扫描@Controller注释,启用spring安全性并设置一些其他的servlet配置

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util"
       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
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <context:component-scan base-package="pl.com.suadeo.nwfm" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <mvc:resources location="/js/" mapping="/js/**"/>
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/img/" mapping="/img/**"/>
    <mvc:resources location="/fonts/" mapping="/fonts/**"/>
    <mvc:resources location="/favicon.ico" mapping="/favicon.ico"/>


    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/static/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:properties/application.properties</value>
            </list>
        </property>
    </bean>

    <!---->
    <!--MULTIPART RESOLVER-->
    <!---->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="52428800"/>
        <property name="maxInMemorySize" value="52428800"/>
    </bean>

    <!---->
    <!--SPRING SECURITY-->
    <!---->
    <security:global-method-security proxy-target-class="true" pre-post-annotations="enabled"/>

</beans>

安全-context.xml中

在安全上下文中,我能够从根上下文中查看bean,因此无需额外的组件扫描

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security.xsd">

    <http pattern="/services/**" security="none"/>
    <http pattern="/css/**" security="none"/>
    <http pattern="/img/**" security="none"/>
    <http pattern="/js/**" security="none"/>
    <http pattern="/fonts/**" security="none"/>
    <http pattern="/favicon.ico" security="none"/>
    <http pattern="/settings/fontSize" security="none"/>

    <http auto-config="false" use-expressions="true">
        <intercept-url pattern="/login*" access="permitAll()"/>
        <intercept-url pattern="/register*" access="permitAll()"/>
        <intercept-url pattern="/qualification/tree*/**" access="permitAll()"/>
        <intercept-url pattern="/**" access="isAuthenticated()"/>
        <form-login login-processing-url="/processLogin" username-parameter="email" password-parameter="password"
                    default-target-url="/" always-use-default-target="false" login-page="/login" authentication-failure-url="/login?error=true"/>
        <logout logout-url="/logout" logout-success-url="/"/>
    </http>

    <beans:bean id="daoAuthenticationProvider"
                class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="userDetailsService"/>
    </beans:bean>

    <beans:bean id="authenticationManager"
                class="org.springframework.security.authentication.ProviderManager">
        <beans:property name="providers">
            <beans:list>
                <beans:ref local="daoAuthenticationProvider"/>
            </beans:list>
        </beans:property>
    </beans:bean>

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

    <beans:bean id="userDetailsService" class="pl.com.suadeo.nwfm.security.UserDetailsServiceImpl"/>

</beans:beans>

<强> UserServiceImpl.java

然后在你的UserServiceImpl中,你可以自动装配你的bean:

public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    public UserDetails loadUserByUsername( String email ) throws UsernameNotFoundException, DataAccessException {
        User userEntity = userRepository.findByEmail( email );
        if ( userEntity == null ) {
            throw new UsernameNotFoundException( "user not found" );
        }

        return userService.buildUserFromUserEntity( userEntity );
    }
}

希望这会有所帮助