楠丶nan
2021-07-02 15:38
采纳率: 100%
浏览 180
已采纳

Sping Security 自定义UserDetailsService 一直报返回值为空异常

使用自定义的UserDetail类作为返回对象,代码如下

@Data
public class CustomUser implements Serializable, UserDetails {

    private String username;

    private String password;

    private boolean state;

    private List<GrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public CustomUser(String username, String password, boolean state, List<GrantedAuthority> authorities) {
        this.username = username;
        this.password = password;
        this.state = state;
        this.authorities = authorities;
    }
}

用UserDetail的实例返回值没问题 一但使用我自己定义的CustomUser作为返回对象就会报空值异常。

@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private UsersDao usersDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            throw new NullPointerException("CustomUserDetailService.loadUserByUsername :空值异常!");
        }
        UsersPOJO user = usersDao.selectOneByUseremailUsersPojo(username);
        if (StringUtils.isEmpty(user)) {
            throw new UsernameNotFoundException("用户不存在!");
        }
        return new User(user.getUseremail(), user.getPassword(), new ArrayList<>());
    }
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

6条回答 默认 最新

  • java通俗易懵 2021-07-02 17:12
    已采纳

    return new User(user.getUseremail(), user.getPassword(), new ArrayList<>()); 你这里传了空list才报空指针吧

    评论
    解决 无用
    打赏 举报
查看更多回答(5条)

相关推荐 更多相似问题