sping:@autowired与构造函数注入

balp4ylt  于 2021-07-23  发布在  Java
关注(0)|答案(0)|浏览(297)

我有一个简单的存储库

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findUserByUsername(String username);
}

1个基本实体用户,包含2个字段、getter和setter
1服务

@Service
public class UserPrincipalDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> optionalUser = userRepository.findUserByUsername(username);
        User user = optionalUser.orElseThrow(() -> new UsernameNotFoundException("Not found username"));

        return new UserPrincipal(user);
    }
}

我的问题是:当我使用@autowired时,这个loaduserbyusername()函数按预期工作,但是当我为userrepository执行构造函数注入时,它抛出一个nullpointerexception?

@Service
public class UserPrincipalDetailsService implements UserDetailsService {

    private UserRepository userRepository;

    public UserPrincipalDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> optionalUser = userRepository.findUserByUsername(username);
        User user = optionalUser.orElseThrow(() -> new UsernameNotFoundException("Not found username"));

        return new UserPrincipal(user);
    }
}

有人遇到过同样的情况吗?
更新:不知道为什么当我一天后再次尝试时,它会正常运行。nullpointerexception没有显示在控制台中,但在我进行调试时会显示出来。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题