SpringSecurity4使用UserDetailsService时无法注入数据库持久层的service、dao
2017-11-24 11:29
344 查看
在使用SpringSecurity4时无法自动注入service层:代码如下:
在执行上段代码是userService一直是空指针异常,后来用dao尝试也是一样,报错NPE,
解决办法:
后来查阅资料发现是因为项目的加载问题,在运行项目时,spring的加载文件还没有加载进来,所以导致无法,对于这种处理方式只需要在启动项目是加载下spring的配置文件:
只要对web.xml添加以下内容即可:
@Service("customUserDetailsService") @Transactional(readOnly = true) public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserService userService; public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { System.out.println("username>>>>"+username); User user = userService.findByUserName(username); System.out.println("user>>>>"+user); if (user == null ){ System.out.println("User not found"); throw new UsernameNotFoundException("Username not found"); } return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassWord(), user.getState().equals("Activite"),true, true,true,getGrantedAuthorities(user)); } private List<GrantedAuthority> getGrantedAuthorities(User user){ List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); for(UserToProfileid userToProfileid : user.getUserToProfileidHashSet()){ System.out.println("userToProfileid : "+userToProfileid); authorities.add(new SimpleGrantedAuthority("ROLE_"+userToProfileid.getProfileid().getType())); } System.out.print("authorities :"+authorities); return authorities; } }
在执行上段代码是userService一直是空指针异常,后来用dao尝试也是一样,报错NPE,
解决办法:
后来查阅资料发现是因为项目的加载问题,在运行项目时,spring的加载文件还没有加载进来,所以导致无法,对于这种处理方式只需要在启动项目是加载下spring的配置文件:
只要对web.xml添加以下内容即可:
<context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:config/spring-security.xml classpath:config/spring-mvc.xml //加载spring配置文件 </param-value> </context-param>
相关文章推荐
- spring security3.x学习(14)_关系型数据库使用的UserDetailsService(JdbcDaoImpl)
- spring security3.x学习(14)_关系型数据库使用的UserDetailsService(JdbcDaoImpl)
- 关于Spring security中自定义UserDetailService无法注入DAO的问题
- 使用MyEclipse中用Hibernate反向工程生成的DAO会发生对象无法存储到数据库的现象,原因是没有运用事务。
- 使用Spring开发中,service接口或者是dao层接口无法注入
- hessian 在spring中的使用 (bean 如 Dao无法注入的问题)
- Spring+Hibernate DAO 持久层开发, Spring 用 Hibernate 访问数据库的三种方法.推荐使用回调
- 在普通Java类里使用spring里注入的service、dao等
- 基于数据库自定义UserDetailsService实现Spring security认证
- 使用spring的@autowired注解,无法实例化dao,service,controller等
- Spring类注册不上,applicationContext不初始化,在Filter中无法getBean、使用Dao、Service等
- Spring+Hibernate DAO 持久层开发, Spring 用 Hibernate 访问数据库的三种方法.推荐使用回调
- Spring使用Quartz定时调度Job无法Autowired注入Service的解决方案
- hessian 在spring中的使用 (bean 如 Dao无法注入的问题)
- SPRING IN ACTION 第4版笔记-第九章Securing web applications-008-使用非关系型数据库时如何验证用户(自定义UserService)
- SpringBoot项目使用注入的Service或DAO时值为空
- 简单MVC三层代码生成器:使用Java从数据库反向生成实体类和action、service、dao代码
- SqlServer:使用普通账户登录win7系统时,无法访问.net软件,原因是sql server 数据库拒绝访问,提示user没有权限
- 使用Spring的Service注入Dao接口需要注意的细节问题
- oracle 12c 无法使用 os 认证登录数据库 ERROR: ORA-01017: invalid username/password; logon denied