我有这样的存储库接口:
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
得到了很好的示例化。发生了什么?
1条答案
按热度按时间wvt8vs2t1#
我建议另一个原因:
此方法可以返回
null
的Integer,这会在自动装箱期间导致NPE,以在