Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

SpringSecurity 自动注入dao出现 NPE如何解决?

### 问题描述
如题:SpringSecurity 自动注入dao出现 NPE,经过大量查找资料后意识到问题的原因为SpringSecurity是基于filter,而filter的初始化在自动bean初始化之前,所以自动注入出现NPE,暂未找到解决的方案因此求助各位大佬

### 相关代码
实现自定义用户认证的代码:

@Service
public class UserDetailServiceImp implements UserDetailsService {
    @Autowired
    UserDao userDao;//此处为问题根本,注入的dao为null
    
    @Override
     public UserDetails loadUserByUsername(String un) throws UsernameNotFoundException {
            //当将此处换位 User user = new user();NPE解决
            //由此可知,问题根本为没有注入的UserDao,但是
            //《Spring 实战第五版》的代码案例注入没有问题
            //是否为Mybaits的问题?(书中使用JPA)
            User user = userDao.getByUsername(un);
            if(user != null){
                return user;
            }
            throw new UsernameNotFoundException("用户:"+user.getUn()+"不存在");
        }
}

UserDao代码(是个mybatis的接口):

public interface UserDao {
    @Insert("INSERT INTO users(id, un, pd, avatar, nickname, email, createAt) VALUES" +
            "(#{user.id}, #{user.un}, #{user.pd}, #{user.avatar}, #{user.nickname}, #{user.email}, #{user.createAt})")
    void register(@Param("user") User user);
    @Select("SELECT * FROM users WHERE un = #{un} or email = #{email}")
    User getByUn(@Param("un") String un, @Param("email") String email);
    @Select("SELECT * FROM users WHERE un = #{un}")
    User getByUsername(@Param("un") String un);
    @Select("SELECT id, pd FROM users WHERE un = #{un} OR email = #{un}")
    LinkedHashMap<String, String> getPd(@Param("un") String un);
    @Select("SELECT * FROM users WHERE id = #{id}")
    User getById(@Param("id")String id);
}

错误提示(与参考中的【https://blog.csdn.net/u013062...】错误提示相同,但那个博主只分析了原因,没有给出解决方案...)

Caused by: java.lang.NullPointerException: null
    at com.zcj.chat.service.UserDetailServiceImp.loadUserByUsername(UserDetailServiceImp.java:24) ~[classes/:na]
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:108) ~[spring-security-core-5.3.4.RELEASE.jar:5.3.4.RELEASE]
    ... 50 common frames omitted

### 你期待的结果是什么?实际看到的错误信息又是什么?

  • 如何在SpringSecurity的filter中注入对象?

问题参考资料:
https://www.cnblogs.com/shamo...
https://blog.csdn.net/ycf9212...
https://blog.csdn.net/u013062...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

这属于spring的范畴,和spring security 没关系
你需要一个UserDao的bean


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...