[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




Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.