关于Spring security中自定义UserDetailService无法注入DAO的问题
2016-12-06 21:14
537 查看
当使用xml配置spring security时,常常在spring-security.xml中使用到如下配置:
<beans:bean id="authenticationProvider"
<!-- 对密码加密算法中使用特定的加密盐及种子 -->
<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对两个文件都是可见的。注入将不会再有问题。
<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对两个文件都是可见的。注入将不会再有问题。
相关文章推荐
- 基于SSH,关于action无法注入service的问题
- 关于ssh框架的service和dao的注入问题
- SpringSecurity4使用UserDetailsService时无法注入数据库持久层的service、dao
- 关于DAO实现类继承JdbcDaoSupport类后,使用注解无法注入DataSource的问题
- 关于用户自定义的userbean出现无法解析的问题
- 在Spring中DAO与Service关于依赖注入写法探讨
- 关于sqlserver 2005 reporting service 中的自定义代码不能调用的问题
- 在VC空项目里添加自定义的预编译头(或关于:无法打开预编译头文件:“Debug/xxx.pch”: No such file or directory的问题的解决)
- 关于配置apache时无法用自定义域名访问论坛的问题
- 关于android studio中添加新的moudle实现自定义view无法引用的问题
- 关于iOS7之后自定义leftnavigationitem后手势无法响应问题的解决办法
- 关于TestNG无法采用Spring注入bean的问题解决
- 关于wcf异常异常信息:由于内部错误,服务器无法处理该请求。有关该错误的详细信息,请打开服务器上的 IncludeExceptionDetailInFaults (从 ServiceBehaviorAttribut
- 关于SpringBoot bean无法注入的问题(与文件包位置有关)
- ssh action中service无法注入,报空指针问题
- Android学习问题:关于AlertDialog中自定义布局带有的EditText无法弹出键盘
- windows无法连接到user profile service服务。此问题阻止标准用户登录系统
- VS2010关于WindowsService 制作安装程序包,无法自动install的问题解决方法
- 关于自定义ViewGroup在ScrollView中无法显示的问题.
- 关于自定义dialog 使用 style 构造器的时候 点击空白无法隐藏的问题