簡體   English   中英

Spring Security:無法自動連接UserDetailsS​​ervice類中的DAO

[英]Spring Security: Unable to autowired DAO in the UserDetailsService class

這個問題已經問了很多遍了,我厭倦了許多解決方案,但是失敗了。

我正在嘗試將用戶映射到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

我的用戶

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)}.

現在,我無法自動將sessionFactory連接到UsersDAOImpl類下。

a添加@Repository注解的UsersDAO實現,因此類可以被包含在組件掃描

@Repository
public class UsersDAOImpl implements UsersDAO {

它是您正在掃描的記憶

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

}

我相信您的配置的問題在於,如果UserDao bean是在不同的上下文(servlet的上下文)中定義的。 SessionFactory ,它不會自動裝配。 我的建議是將普通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 );
    }
}

希望這會有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM