我有一个正在开发的Spring REST API,由于某种原因一直返回NullReferenceException。我不知道为什么。下面是我的代码:
接口:
public interface InitiativesService {
InitiativeDto createInitiative(InitiativeDto initiativeDto);
}
实现的类:
public class InitiativeServiceImpl implements InitiativesService {
private final InitiativeRepository initiativeRepository;
@Autowired
public InitiativeServiceImpl(InitiativeRepository initiativeRepository)
{
this.initiativeRepository = initiativeRepository;
}
@Override
public InitiativeDto createInitiative(InitiativeDto initiativeDto) {
initiativeRepository.Save(initiativeDto);
}
与dB通信的Repository类:
@Repository
public interface InitiativeRepository extends JpaRepository<Initiative, Long> {}
最后是控制器
public class InitiativesController {
private InitiativesService initiativesService;
public InitiativesController(InitiativesService initiativesService) {
this.initiativesService = initiativesService;
}
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<InitiativeDto> createInitiative(@Valid @RequestBody InitiativeDto initiative) {
log.info("Saving");
InitiativeDto createdInitiative = initiativesService.createInitiative(initiative);
return ResponseEntity.status(HttpStatus.CREATED).body(createdInitiative);
}
当我尝试运行这个并通过邮差测试时,它返回一个NullPointerException。我调试它,我可以看到initiativeservice是空的。我很困惑,因为我有相同的实现来创建没有这个问题的用户。有人能指出我这里的问题吗?
在构造函数中添加@Autowired
注释以自动连接initiativeService
@Autowired
public InitiativesController(InitiativesService initiativesService) {
this.initiativesService = initiativesService;
}