我正在开发一个springrestapi,由于某种原因,它不断返回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);
}
用于与数据库通信的存储库类:
@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);
}
当我尝试运行这个并通过postman进行测试时,它返回一个nullpointerexception。我调试它,我可以看到initiativesservice为空。我很困惑,因为我有相同的实现来创建用户,没有这个问题也可以正常工作。有人能看出我这里有什么问题吗?
1条答案
按热度按时间bsxbgnwa1#
添加
@Autowired
构造函数上的注解以自动关联initiativeService
```@Autowired
public InitiativesController(InitiativesService initiativesService) {
this.initiativesService = initiativesService;
}