I already know that this is a very common error and it happens when trying to access a NULL type object, the problem is that I do not know why it is NULL if I'm supposed to be instantiating it, I have a class called NoteController in the that instantiates an object of another class called CountryController, this CountryController class has a simple method that returns True or False when it makes a query to the database, I need to call this method from the NoteController class but it always throws the exception NullPointerException, ¿Any do you know why? ... in advance Thank you very much ..
// This is my NoteController class
//CLASE NoteController
package com.myapp.controller;
import com.myapp.model.Notes;
import com.myapp.repository.NoteRepository;
import com.myapp.controller.CountryController;
@RestController
@RequestMapping("/api")
public class NoteController {
@Autowired
NoteRepository noteRepository;
CountryController objCountry = new CountryController();
//Create a new Note Validation Country
@PostMapping("/notes")
public String createNote(@Valid @RequestBody Notes note) {
try {
if (objCountry.existCountry((note.getNOT_COUNTRY()))) {
noteRepository.save(note);
return "Nota Guardada";
}else {
return "Nota no Guardada";
}
}catch(NullPointerException e) {
return "Se produjo un error "+ e;
}
}
}
// THIS IS MY CountryController CLASS
//Clase CountryController
package com.myapp.controller;
import com.MyApp.model.Country;
import com.MyApp.repository.CountryRepository;
@RestController
@RequestMapping("/api")
public class CountryController {
public CountryController() {}
@Autowired
CountryRepository countryRepository;
//Verify Country
public Boolean existCountry(String countryId) {
if (countryRepository.findById(countryId).isPresent()) {
return true;
}else {
return false;
}
}
}