Issue
I keep on running into the following error:
java.lang.NullPointerException: Cannot invoke "com.example.cinema.Repository.VideosRepository.save(Object)" because "com.example.cinema.Service.VideoService.videoRepository" is null
the error also happens when I try to do the getall call as well.
here is my code set up
controller:
@RestController
public class VideosController {
@Autowired
private VideoService videoService;
@Autowired
private VideosRepository videoRepository;
@RequestMapping("/videos/getAll")
public List<Videos> getAll(){
System.out.println("called");
return videoService.getAll();
}
@PostMapping("/videos/create")
@ResponseBody
public String create(@RequestBody Videos videos) {
System.out.println(videos.getTitle());
videoService.create(videos);
return "Thanks For Posting!!!";
}
}
services
@Service
public class VideoService {
@Autowired
private static VideosRepository videoRepository;
public List<Videos> getAll(){
return videoRepository.findAll();
}
public static Videos create(Videos videos) {
return videoRepository.save(videos);
}
}
Repository
@Repository
public interface VideosRepository extends MongoRepository<Videos, String>
{
List<Videos> findByTitle(String title);
}
Solution
Here is the error
@Autowired
private static VideosRepository videoRepository;
remove static
!
Spring can't autowire to static fields as those are created when the class is loaded initially in JVM and are for common use between different java instances. Spring instead instantiates specific java instances.
Answered By - Panagiotis Bougioukos
Answer Checked By - Cary Denson (JavaFixing Admin)