SpringSecurity4使用UserDetailsService时无法注入数据库持久层的service、dao

在使用SpringSecurity4时无法自动注入service层:代码如下:

@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 getGrantedAuthorities(User user){
        List authorities = new ArrayList();
        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>

你可能感兴趣的:(java)