Reputation: 409
I have a Spring REST API I am developing that keeps returning a NullReferenceException for some reason. I can't figure out why. Here is my code:
The interface:
public interface InitiativesService {
InitiativeDto createInitiative(InitiativeDto initiativeDto);
}
The class that implements it:
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);
}
The Repository class for communicating to the dB:
@Repository
public interface InitiativeRepository extends JpaRepository<Initiative, Long> {}
And lastly the controller:
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);
}
When I try running this and testing via Postman, it returns a NullPointerException. I debug it and I can see the initiativesService is null. I am confused as I have the same implementation for creating Users which works fine without this issue. Can anyone spot any problems I have here?
Upvotes: 1
Views: 78
Reputation: 856
Add @Autowired
annotation on your constructor to autowire your initiativeService
@Autowired
public InitiativesController(InitiativesService initiativesService) {
this.initiativesService = initiativesService;
}
Upvotes: 1