Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring keeps saying Repository is null everytime i do calls

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading