您的位置:首页 > 编程语言 > Java开发

关于Spring security中自定义UserDetailService无法注入DAO的问题

2016-12-06 21:14 537 查看
当使用xml配置spring security时,常常在spring-security.xml中使用到如下配置:
<beans:bean id="authenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="myUserDetailService"/>
<beans:property name="hideUserNotFoundExceptions" value="false"/>
<beans:property name="passwordEncoder" ref="passwordEncoder"></beans:property>


 

<!-- 对密码加密算法中使用特定的加密盐及种子 -->   

 <beans:property name="saltSource" ref="saltSource"></beans:property>

</beans:bean>这里的myUserDetailService即为自定义的用户信息处理类,比如下面的代码:

package com.napchen.digital.service.impl;

import com.napchen.digital.bean.Authority;import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.core.userdetails.User;

import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;import java.util.HashSet;

import java.util.List;import java.util.Set;

/** 

* Created by NapChen on 2016/11/30 0030.

 */

public class MyUserDetailServiceImpl implements UserDetailsService {   

 private com.napchen.digital.bean.User user;  

  @Autowired   

  @Qualifier("userServiceImpl")    

private UserServiceImpl userServiceImpl;    

@Autowired    private AuthorityServiceImpl authoriryService;    

@Override    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {        

System.out.println("-----------------------------------");     

   System.out.println(userName);        System.out.println("-----------------------------------");

        user = userServiceImpl.login(userName);

        if (user == null) {

            throw new UsernameNotFoundException("未能找到用户名为" + userName + "的用户");       

 }

        System.out.println("----------------用户查找完毕----------------");

        System.out.println("-----------开始查找用户权限信息-----------------");

        List<Authority> authorities = authoriryService.findUserAuthorityByUsername(userName);

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

        for (int i = 0; i < authorities.size(); i++) {

            authoritiesRet.add(new SimpleGrantedAuthority(authorities.get(i).getAuthority()));

            System.out.println("权限" + i + ":" + authorities.get(i).getAuthority());

        }

        System.out.println("------------权限查找完毕---------------");

        UserDetails userDetails = new User(userName, user.getPassword(),

                user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(),

                user.isAccountNonLocked(), authoritiesRet);

        return userDetails;

    }

}

经常的一个问题是,如果你的serviceImplement是在spring-servlet.xml中扫描注入的,这里的userServiceImpl和authoriryService会报nullPointException,Debug模式下可以看到在调用user = userServiceImpl.login(userName)时,userServiceImpl为null。查看log日志可以发现,spring-security.xml的配置文件在spring-servlet.xml之前加载,这就意味着MyUserDetailServiceImpl
在实例化之前,serviceImpl并没有实例化。

一种可行的方式是引入applicationContext.xml文件,在web.xml中配置如下:

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

<!--<context-param>-->

    <!--<param-name>contextConfigLocation</param-name>-->

    <!--<param-value>classpath:spring-security.xml</param-value>-->

<!--</context-param>-->

注意:注释类容是不需要的,pring-security.xml文件我们在applicationContext.xml中引入同时添加listener

<listener>

    <listener-class>

        org.springframework.web.context.ContextLoaderListener

    </listener-class>

</listener>

最好的方式是在applicationContext.xml初始化基本的bean,只在spring-servlet.xml中扫描Controller所在的包。

以下是applicationContext.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:tx="http://www.springframework.org/schema/tx" 

      xmlns:context="http://www.springframework.org/schema/context"

       xmlns:mvc="http://www.springframework.org/schema/mvc"

       xmlns:aop="http://www.springframework.org/schema/aop" 

      xsi:schemaLocation="http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- 引入jdbc配置文件 -->

    <bean id="propertyConfigurer"

          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

        <property name="locations">

            <list>

                <value>classpath:jdbc.properties</value>

            </list>

        </property>

    </bean>

    <!-- 配置数据源 -->

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">

        <property name="driverClassName" value="${driverClassName}"></property>

        <property name="url" value="${url}"></property>

        <property name="username" value="${username}"></property>

        <property name="password" value="${password}"></property>

        <property name="initialSize" value="${initialSize}"></property>

        <property name="maxIdle" value="${maxIdle}"></property>

        <property name="minIdle" value="${minIdle}"></property>

        <property name="maxActive" value="${maxActive}"></property>

        <property name="maxWait" value="${maxWait}"></property>

        <property name="validationQuery" value="${validationQuery}"></property>

    </bean>

    <!-- 事务管理 -->

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="transactionManager"

          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSource"></property>

     
a39f
  <property name="rollbackOnCommitFailure" value="true"></property>

    </bean>

    <!-- 启用aspectj注解自动代理 -->    <!-- ====================================== -->

    <context:annotation-config/>

    <!--<context:component-scan base-package="com.napchen.digital.controller"></context:component-scan>-->

    <context:component-scan base-package="com.napchen.digital.bean"></context:component-scan>

    <context:component-scan base-package="com.napchen.digital.service.impl"></context:component-scan>

    <context:component-scan base-package="com.napchen.digital.handle"></context:component-scan>

    <!-- ==================spring和MyBatis整合========================================== -->

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        <property name="dataSource" ref="dataSource"/>

        <!-- 自动扫描mapping.xml文件 -->

        <property name="mapperLocations">

            <list>

                <value>classpath*:com/napchen/digital/mapper/*.xml</value>

            </list>

        </property>

    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

        <property name="basePackage" value="com.napchen.digital.dao"/>

        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>

    </bean>

    <!-- ==================================================================================== -->

    <import resource="classpath:spring-servlet.xml"></import>

    <import resource="classpath:spring-security.xml"></import>

</beans>

在这里导入两个配置文件

<import resource="classpath:spring-servlet.xml"></import>

<import resource="classpath:spring-security.xml"></import>

这样在rootcontext中初始化的bean对两个文件都是可见的。注入将不会再有问题。








                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐