This question already has answers here:
Why is my Spring @Autowired field null?
                                
                                    (17个答案)
                                
                        
                2年前关闭。
            
        

我是春天的新手,我正在尝试创建自己的用户并进行身份验证。到目前为止,一切正常,我可以登录和注销,但是无法在身份验证成功/失败处理程序中自动连接用户存储库。我可以在其他任何地方执行此操作,例如在控制器中。

我的处理程序如下所示:

@Service
public class MyAuthenticationSuccessHandler extends
SavedRequestAwareAuthenticationSuccessHandler {

@Autowired
UserRepository userRepository;

@Override
public void onAuthenticationSuccess(HttpServletRequest request,
                                    HttpServletResponse response, Authentication authentication)
        throws ServletException, IOException {
    [...]
    User user = (User)authentication.getPrincipal();
    user.setLastLogin(now);
    userRepository.save(user);
    [...]
}
}


当我尝试保存用户时,我收到一个nullpointer异常,因为userrepository为null。

用户存储库如下所示:

@Repository
public interface UserRepository extends CrudRepository<User, Long> {
Optional<User> findByName(String name);
}


但是,我可以像在Sucesshandler中尝试的一样,在其他任何地方对其进行自动布线。例如在控制器中。

有人可以告诉我我在做什么错吗?

最佳答案

当我使用此类时,我用@Component而不是@Service注释它(美学)。

如果此时获得NPE,那是因为MyAuthenticationSuccessHandler未被管理。您已扫描软件包或在@Bean类中对其进行了扫描。

07-26 09:39
查看更多