spring 系统信息库Bean未示例化

5anewei6  于 2022-11-28  发布在  Spring
关注(0)|答案(1)|浏览(162)

我有这样的存储库接口:

public interface ScoreCardRepository extends CrudRepository<ScoreCard, Long> {

    @Query(value = "SELECT SUM(SCORE) FROM SCORE_CARD WHERE USER_ID = :userId", nativeQuery = true)
    Integer getTotalScoreForUser(Long userId);
}

以及该控制器:

@RestController
@RequestMapping("/gamification")
public class GamificationController {

    private final LeaderBoardServiceImpl leaderBoardService;

    private final GameServiceImpl gameService;

    @Autowired
    public GamificationController(GameServiceImpl gameService, LeaderBoardServiceImpl leaderBoardService){
        this.gameService = gameService;
        this.leaderBoardService = leaderBoardService;
    }

    @GetMapping("/retrieve-stats")
    ResponseEntity<GameStats> getUserStats(@RequestParam("user") String userId){
        return ResponseEntity.ok(gameService.retrieveStatsForUser(Long.parseLong(userId)));
    }

}

现在,当我调用/retrieve-stats并进入gameService.retrieveStatsForUser内部时,我得到一个空指针异常

@Service
public class GameServiceImpl implements GameService {

    private final ScoreCardRepository scoreCardRepository;

    private final BadgeCardRepository badgeCardRepository;

    @Autowired
    public GameServiceImpl(ScoreCardRepository scoreCardRepository, BadgeCardRepository badgeCardRepository) {
        this.scoreCardRepository = scoreCardRepository;
        this.badgeCardRepository = badgeCardRepository;
    }

    @Override
    public GameStats retrieveStatsForUser(Long userId) {
        List<BadgeCard> badgeCardList = badgeCardRepository.findByUserIdOrderByBadgeTimestampDesc(userId);
--->>>  int totalScore = scoreCardRepository.getTotalScoreForUser(userId); //NULL POINTER EXCEPTION
        GameStats gameStats = new GameStats(userId, totalScore,
                badgeCardList.stream().map(BadgeCard::getBadge).collect(Collectors.toList()));
        return gameStats;
    }
}

这是否意味着scoreCardRepository bean没有被示例化?这应该在@Autowired GamificationserviceImpl构造函数中发生,对吗?badgeCardRepository得到了很好的示例化。发生了什么?

wvt8vs2t

wvt8vs2t1#

我建议另一个原因:

Integer getTotalScoreForUser(Long userId);

此方法可以返回nullInteger,这会在自动装箱期间导致NPE,以在

int totalScore = scoreCardRepository.getTotalScoreForUser(userId);

相关问题