【问题标题】:Spring Security: Unable to autowired DAO in the UserDetailsService classSpring Security:无法在 UserDetailsS​​ervice 类中自动装配 DAO
【发布时间】:2015-09-14 22:45:00
【问题描述】:

这个问题已经被问过很多次了,我累了很多解决方案但都失败了。

我正在尝试将用户映射到 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);

}

我的 UsersDAOImpl 是:

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 更改为:

我的 UsersDAOImpl 是:

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。

【问题讨论】:

  • 你能分享一下用于加载 spring bean 的 web.xml 条目吗?你可能有两个 spring 上下文。
  • 我已经添加了我的 web.xml。
  • 这看起来不错。应用程序启动日志将显示更多详细信息。数据库连接或 hbm 文件可能有问题。
  • 问题不在于放置@repository 注释。但是,也出现了类似的问题。不幸的是,现在 sessionFactory 没有自动装配。

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


【解决方案1】:

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

@Repository
public class UsersDAOImpl implements UsersDAO {

【讨论】:

  • 谢谢回答,但现在我得到了这个错误:原因:org.springframework.beans.factory.BeanCreationException:无法自动装配字段:私有 org.hibernate.SessionFactory com.memorize.dao.impl .UsersDAOImpl.sessionFactory;没有为依赖找到[org.hibernate.SessionFactory]类型的合格bean:预计至少有1个bean有资格作为此依赖的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}。
【解决方案2】:

你正在扫描 com.memorize 是对的

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

但只有带有 @controller、@service、@component、@Repository 等注释的类才能成为自动关联的候选对象,而其他类则不是。因此请考虑相应地注释您的类以进行正确的自动关联。

@Component --> 任何 Spring 管理的组件的通用原型

@Repository--> 持久层的原型

@Service --> 服务层的原型

@Controller --> 表示层的原型(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);
}

}

【讨论】:

  • 谢谢回答,但现在我得到了这个错误:原因:org.springframework.beans.factory.BeanCreationException:无法自动装配字段:私有 org.hibernate.SessionFactory com.memorize.dao.impl .UsersDAOImpl.sessionFactory;没有为依赖找到[org.hibernate.SessionFactory]类型的合格bean:预计至少有1个bean有资格作为此依赖的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}。
  • 可以分享一下UsersDAOImpl中的import语句吗?
  • 我再次编辑了我的问题。我真的不明白为什么我会遇到 sessionFactory 错误。没有安全部分的项目工作正常。添加安全部分后,事情开始无法正常工作。
【解决方案3】:

我相信你的配置的问题是UserDao bean 如果在不同的上下文中定义(servlet 的那个)。 SessionFactory 也一样,它不会自动连接。我的建议是将 common bean 移动到 root-context,它同时加载到 servlet 和 securitie 的上下文中。

一个例子:

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

security-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 );
    }
}

希望这会有所帮助

【讨论】:

    猜你喜欢
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2014-08-22
    • 2013-02-11
    • 2013-05-12
    相关资源
    最近更新 更多