-1

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);
    
    
    
    
}
htmlhelp32
  • 141
  • 1
  • 12
  • Check this : https://stackoverflow.com/questions/1018797/can-you-use-autowired-with-static-fields – Nemanja Jul 14 '22 at 08:27

1 Answers1

2

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.

Panagiotis Bougioukos
  • 15,955
  • 2
  • 30
  • 47