[fix] NullPointerException Cannot Invoke findById because Repository is null - Java Spring




Exception Stacktrace Extract:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception 
[Request processing failed: java.lang.NullPointerException: 
Cannot invoke "org.code2care.todolist.todolist.entities.ToDoRepository.findById(Object)" 
because "this.toDoRepository" is null]


Reason:

The reason for this error is that you have defined a member variable of your Repository class in the Spring Controller class but have not @Autowired it. As it is not injected by the Spring IoC container, you get a NullPointerException when you try to do an operation over it



Solution:

Make sure you add @Autowired annotation above all your repositories in the Controller class,

Example:
@Autowired
private ToDoListRepository toDoListRepository;
    
@Autowired
private ToDoRepository toDoRepository;


Fix - NullPointerException Cannot Invoke findById because Repository is null


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap