The repository is not injected. In LoginController either create a constructor with your repositories (preferable way) or mark fields as @Autowired.

Answer from Max Farsikov on Stack Overflow
🌐
OneUptime
oneuptime.com › home › blog › how to handle 'cannot invoke method on null' errors
How to Handle 'Cannot invoke method on null' Errors
December 22, 2025 - public class UserPreferences { private String theme; private String language; private Integer pageSize; public String getTheme() { return theme != null ? theme : "light"; } public String getLanguage() { return language != null ? language : "en"; } public int getPageSize() { return pageSize != null ? pageSize : 20; } } // Or use Lombok (@Builder.Default requires @Builder on the class) @Data @Builder public class UserPreferences { @Builder.Default private String theme = "light"; @Builder.Default private String language = "en"; @Builder.Default private Integer pageSize = 20; } import org.springfr
Discussions

Spring Boot Test cannot give a clear message but throw NPE now when @SpringBootConfiguration cannot be found
When we try spring boot test without @SpringBootConfiguration,NPE exception will occur. Before supporting AOT,it throws IllegalStateException with message: Unable to find a @SpringBootConfiguration, you need to use " + "@ContextConfigura... More on github.com
🌐 github.com
1
November 26, 2022
Spring: NullPointerException trying to access findAll() @Repository
I think you should provide more code to answer your question. More on reddit.com
🌐 r/javahelp
14
3
February 23, 2022
rest - Spring Boot - Null Pointer Exception - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
July 11, 2023
java - Spring Boot Unit test gives error: Cannot invoke "" because "this.taskService" is null - Stack Overflow
I'm trying to unit test my service class and the repository. I want to test whether the code will correctly create and read the data. I mock the repo but when I run the test it just says: java.lang. More on stackoverflow.com
🌐 stackoverflow.com
People also ask

Spring Boot NullPointerException
- Bottom line: 90% of Spring Boot NPEs come from 4 root causes: (1) calling new instead of letting Spring inject the bean, (2) missing @Component/@Service annotation, (3) calling injected fields before construction completes, or (4) accessing a scoped bean outside its scope.
🌐
knowledgelib.io
knowledgelib.io › home › software › debugging › how to fix nullpointerexception in spring boot
How to Fix NullPointerException in Spring Boot | knowledgelib.io
How do I fix NullPointerException in Spring Boot?
- Bottom line: 90% of Spring Boot NPEs come from 4 root causes: (1) calling new instead of letting Spring inject the bean, (2) missing @Component/@Service annotation, (3) calling injected fields before construction completes, or (4) accessing a scoped bean outside its scope.
🌐
knowledgelib.io
knowledgelib.io › home › software › debugging › how to fix nullpointerexception in spring boot
How to Fix NullPointerException in Spring Boot | knowledgelib.io
NullPointerException Spring service
- Bottom line: 90% of Spring Boot NPEs come from 4 root causes: (1) calling new instead of letting Spring inject the bean, (2) missing @Component/@Service annotation, (3) calling injected fields before construction completes, or (4) accessing a scoped bean outside its scope.
🌐
knowledgelib.io
knowledgelib.io › home › software › debugging › how to fix nullpointerexception in spring boot
How to Fix NullPointerException in Spring Boot | knowledgelib.io
🌐
GitHub
github.com › spring-projects › spring-boot › issues › 33370
Spring Boot Test cannot give a clear message but throw NPE now when @SpringBootConfiguration cannot be found · Issue #33370 · spring-projects/spring-boot
November 26, 2022 - java.lang.NullPointerException: Cannot invoke "java.lang.Class.getName()" because "found" is null at org.springframework.boot.test.context.SpringBootTestContextBootstrapper.findConfigurationClass(SpringBootTestContextBootstrapper.java:261)
Author: spring-projects
🌐
Knowledgelib
knowledgelib.io › home › software › debugging › how to fix nullpointerexception in spring boot
How to Fix NullPointerException in Spring Boot | knowledgelib.io
May 17, 2026 - If you wire your own beans through generic Spring APIs and your module is @NullMarked, parameters that used to silently accept null may now require explicit @Nullable — NullAway/IDE will flag them at compile time.
🌐
Reddit
reddit.com › r/javahelp › spring: nullpointerexception trying to access findall() @repository
r/javahelp on Reddit: Spring: NullPointerException trying to access findAll() @Repository
February 23, 2022 -

java.lang.NullPointerException: Cannot invoke "com.example.demo.student.StudentRepository.findAll()" because "this.studentRepository" is null

I do have a @Repository annotated above my StudentRepository class. I also used @Autorwired above the constructor in my StudentService class. I think the problem is with dependency injection but I don't see why.

Related code:

//StudentRepository.java
package com.example.demo.student;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}

//StudentService.java
package com.example.demo.student;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.Month;
import java.util.List;

@Service
public class StudentService {

    private final StudentRepository studentRepository;

    @Autowired
    public StudentService(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    public List<Student> getStudents() {
        return studentRepository.findAll();
    }
}

//StudentController.java
package com.example.demo.student;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(path = "api/v1/student")
public class StudentController {

    private final StudentService studentService;

    @Autowired
    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    @GetMapping
    public List<Student> getStudents(StudentService studentService) {
        return studentService.getStudents();
    }
}
Find elsewhere
🌐
GitHub
github.com › spring-projects › spring-boot › issues › 29531
Cannot invoke "java.lang.Class.isInterface()" because "typeToRead" is null · Issue #29531 · spring-projects/spring-boot
When using Spring data JPA projection, the application is failing to start with the following error: Caused by: java.lang.NullPointerException: Cannot invoke "java.lang.Class.isInterface()" because "typeToRead" is null at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:181) ~[spring-data-jpa-2.6.1.jar:2.6.1] at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:152) ~[spring-data-jpa-2.6.1.jar:2.6.1] at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:59) ~[spring-dat
Author: spring-projects
🌐
GitHub
github.com › spring-projects › spring-kafka › issues › 2914
Spring Boot 3.2.0 > java.lang.NullPointerException: Cannot invoke "kafka.raft.KafkaRaftManager.apiVersions()" because the return value of "kafka.server.SharedServer.raftManager()" is null · Issue #2914 · spring-projects/spring-kafka
November 24, 2023 - Spring Boot 3.2.0 > java.lang.NullPointerException: Cannot invoke "kafka.raft.KafkaRaftManager.apiVersions()" because the return value of "kafka.server.SharedServer.raftManager()" is null#2914
Author: spring-projects
🌐
GitHub
github.com › spring-projects › spring-boot › issues › 34363
NullPointerException when using Spring Data JPA native queries in Spring Boot 2.7.9 and 3.0.3 · Issue #34363 · spring-projects/spring-boot
February 24, 2023 - My build randomly stopped working today. After a couple hours of troubleshooting looking at some useless errors, my coworkers and I figured out that updating to 2.7.9 was what broke things. (we aut...
Author: spring-projects
🌐
Stack Overflow
stackoverflow.com › questions › 71448503 › spring-boot-cant-invoke-service-because-service-is-null-exception
nullpointerexception - Spring boot can't invoke Service because Service is null exception - Stack Overflow
This is Exception: enter code herejava.lang.NullPointerException: Cannot invoke "com.company.MedicalManagement.repository.DoctorRepository.findById(Object)" because "this.doctorRepository" is null
🌐
GitHub
github.com › spring-projects › spring-boot › issues › 28794
because "this.condition" is null · Issue #28794 · spring-projects/spring-boot
November 24, 2021 - 2021-11-24 10:45:19,845 ERROR [restartedMain] o.s.boot.SpringApplication [SpringApplication.java : 819] Application run failed org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) at org.springframework.context.support.DefaultLifecycleProcessor
Author: spring-projects
🌐
Reddit
reddit.com › r/javahelp › repositorys returning nullpointerexception when calling jparepository save
r/javahelp on Reddit: Repositorys returning NullPointerException when calling JpaRepository save
December 9, 2023 -

I'm pretty new at Java and was trying to do a CRUD, the process was going pretty smoothly until i had to make the create function to the table with a composite key.

At first i thought the problem was with the Dependecy Injection, but it's working just fine in the methods getByStateAndModelId() and getAll().I also tried to set the names for the EquipmentModel and EquipmentState in the createEmshe (In the POST i just insert the Id of both State and Models, and the Value, so the names from Model and State coming from the DTO are null and i thought that maybe that was the cause). But then, both the equipmentModelRepository and the equipmentStateRepository returned the NullPointerException too, what i'm missing?here's the relevant code:

The service:

package com.api.forestoperation.emshe;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.api.forestoperation.equipmentmodel.EquipmentModelModel;
import com.api.forestoperation.equipmentmodel.EquipmentModelRepository;
import com.api.forestoperation.equipmentstate.EquipmentStateModel;
import com.api.forestoperation.equipmentstate.EquipmentStateRepository;

@Service
public class EquipmentModelStateHourlyEarningsService {
	@Autowired
	EquipmentModelStateHourlyEarningsRepository emsheRepository;
	@Autowired
	EquipmentModelRepository equipmentModelRepository;
	@Autowired
	EquipmentStateRepository equipmentStateRepository;

	public List<EquipmentModelStateHourlyEarningsModel> getAllEmshe() {
		return emsheRepository.findAll();
	}

	public EquipmentModelStateHourlyEarningsModel createEmshe(EquipmentModelStateHourlyEarningsDTO emsheDTO) {
		var emsheModel = new EquipmentModelStateHourlyEarningsModel();

		BeanUtils.copyProperties(emsheDTO, emsheModel);

		EquipmentModelModel emsheModelInfo = emsheModel.getId().getEquipmentModel();
		EquipmentStateModel emsheStateInfo = emsheModel.getId().getEquipmentState();
		EquipmentModelStateHourlyEarningsPK emshePk = new EquipmentModelStateHourlyEarningsPK(emsheModelInfo,
				emsheStateInfo);

		emsheModel.setId(emshePk);

		return emsheRepository.save(emsheModel);
	}

	public EquipmentModelStateHourlyEarningsModel getEmsheByStateAndModelId(UUID modelId, UUID stateId) {
		var modelExists = equipmentModelRepository.findById(modelId).orElse(null);
		var stateExists = equipmentStateRepository.findById(stateId).orElse(null);
		if (modelExists != null && stateExists != null) {
			EquipmentModelStateHourlyEarningsPK emshePk = new EquipmentModelStateHourlyEarningsPK(modelExists,
					stateExists);
			EquipmentModelStateHourlyEarningsModel emsheModel = emsheRepository.findById(emshePk).orElse(null);
			return emsheModel;
		}
		return null;
	}
}

The Controller:

package com.api.forestoperation.emshe;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EquipmentModelStateHourlyEarningsController {
	@Autowired
	EquipmentModelStateHourlyEarningsService emsheService;

	@PostMapping("/equipment-model-state-hourly-earnings")
	public ResponseEntity<Object> saveEmshe(@RequestBody EquipmentModelStateHourlyEarningsDTO emsheDTO) {
		var savedEmshe = new EquipmentModelStateHourlyEarningsService().createEmshe(emsheDTO);
		return savedEmshe != null
				? ResponseEntity.status(HttpStatus.CREATED)
						.body("EquipmentModelStateHourlyEarnings created with Sucess")
				: ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
	}

	@GetMapping("/equipment-model-state-hourly-earnings")
	public ResponseEntity<List<EquipmentModelStateHourlyEarningsModel>> getAllEmshe() {
		List<EquipmentModelStateHourlyEarningsModel> equipments = emsheService.getAllEmshe();
		return ResponseEntity.status(HttpStatus.OK).body(equipments);
	}

	@GetMapping("/equipment-model-state-hourly-earnings/{modelId}/{stateId}")
	public ResponseEntity<Object> getEmsheByModelAndStateId(@PathVariable(value = "modelId") UUID modelId,
			@PathVariable(value = "stateId") UUID stateId, EquipmentModelStateHourlyEarningsPK emshePk) {
		EquipmentModelStateHourlyEarningsModel emsheModel = emsheService.getEmsheByStateAndModelId(modelId, stateId);
		return emsheModel == null ? ResponseEntity.status(HttpStatus.BAD_REQUEST).body("EMSHE nulo")
				: ResponseEntity.status(HttpStatus.OK).body(emsheModel);

	}
}

The Repository:

	package com.api.forestoperation.equipment;

import java.util.UUID;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EquipmentRepository extends JpaRepository<EquipmentModel, UUID> {

}

The Model:

	package com.api.forestoperation.emshe;

import java.io.Serializable;

import com.api.forestoperation.equipmentmodel.EquipmentModelModel;
import com.api.forestoperation.equipmentstate.EquipmentStateModel;

import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;

@Entity
@Table(name="equipment_model_state_hourly_earnings", schema="operation")
public class EquipmentModelStateHourlyEarningsModel implements Serializable {
	@EmbeddedId
	private EquipmentModelStateHourlyEarningsPK id;
	private static final long serialVersionUID = 1L;
	
	@Column(name="value")
	private double value;
	
	public EquipmentModelStateHourlyEarningsPK getId() {
		return id;
	}

	public void setId(EquipmentModelStateHourlyEarningsPK id) {
		this.id = id;
	}

	public double getValue() {
		return value;
	}

	public void setValue(double value) {
		this.value = value;
	}
	
	
	public EquipmentModelModel getEquipmentModel() {
		return id.getEquipmentModel();
	}
	
	public EquipmentStateModel getEquipmentState() {
		return id.getEquipmentState();
	}

}

The Pk:

package com.api.forestoperation.emshe;

import java.io.Serializable;
import java.util.Objects;

import com.api.forestoperation.equipmentmodel.EquipmentModelModel;
import com.api.forestoperation.equipmentstate.EquipmentStateModel;

import jakarta.persistence.Embeddable;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;

@Embeddable
public class EquipmentModelStateHourlyEarningsPK implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@ManyToOne
	@JoinColumn(name = "equipment_model_id")
	private EquipmentModelModel equipmentModel;

	@ManyToOne
	@JoinColumn(name = "equipment_state_id")
	private EquipmentStateModel equipmentState;

	public EquipmentModelStateHourlyEarningsPK() {

	}

	public EquipmentModelStateHourlyEarningsPK(EquipmentModelModel equipmentModelModel,
			EquipmentStateModel equipmentStateModel) {
		this.equipmentModel = equipmentModelModel;
		this.equipmentState = equipmentStateModel;
	}

	@Override
	public int hashCode() {
		return Objects.hash(equipmentModel, equipmentState);
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		EquipmentModelStateHourlyEarningsPK other = (EquipmentModelStateHourlyEarningsPK) obj;
		return Objects.equals(equipmentModel, other.equipmentModel)
				&& Objects.equals(equipmentState, other.equipmentState);
	}

	public EquipmentModelModel getEquipmentModel() {
		return equipmentModel;
	}

	public void setEquipmentModel(EquipmentModelModel equipmentModel) {
		this.equipmentModel = equipmentModel;
	}

	public EquipmentStateModel getEquipmentState() {
		return equipmentState;
	}

	public void setEquipmentState(EquipmentStateModel equipmentState) {
		this.equipmentState = equipmentState;
	}
}

Here's the error i get:

java.lang.NullPointerException: Cannot invoke     "com.api.forestoperation.emshe.EquipmentModelStateHourlyEarningsRepository.save(Object)" because "this.emsheRepository" is null
at com.api.forestoperation.emshe.EquipmentModelStateHourlyEarningsService.createEmshe(EquipmentModelStateHourlyEarningsService.java:39) ~[classes/:na]
at com.api.forestoperation.emshe.EquipmentModelStateHourlyEarningsController.saveEmshe(EquipmentModelStateHourlyEarningsController.java:22) ~[classes/:na]
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-6.0.13.jar:6.0.13]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-6.0.13.jar:6.0.13]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:118) ~[spring-webmvc-6.0.13.jar:6.0.13]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884) ~[spring-webmvc-6.0.13.jar:6.0.13]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-6.0.13.jar:6.0.13]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-6.0.13.jar:6.0.13]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1081) ~[spring-webmvc-6.0.13.jar:6.0.13]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:974) ~[spring-webmvc-6.0.13.jar:6.0.13]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1011) ~[spring-webmvc-6.0.13.jar:6.0.13]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:914) ~[spring-webmvc-6.0.13.jar:6.0.13]
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590) ~[tomcat-embed-core-10.1.15.jar:6.0]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885) ~[spring-webmvc-6.0.13.jar:6.0.13]
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658) ~[tomcat-embed-core-10.1.15.jar:6.0]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) ~[tomcat-embed-websocket-10.1.15.jar:10.1.15]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-6.0.13.jar:6.0.13]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.13.jar:6.0.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-6.0.13.jar:6.0.13]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.13.jar:6.0.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-6.0.13.jar:6.0.13]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.13.jar:6.0.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-10.1.15.jar:10.1.15]
at java.base/java.lang.Thread.run(Thread.java:1583) ~[na:na]

Top answer
1 of 4
4
Your EquipmentModelStateHourlyEarningsRepository isn't being injected into your EquipmentModelStateHourlyEarningsService. You would have to provide your spring configuration for us to troubleshoot it properly (or even better provide full source of project). You should really be using constructors instead of putting `@Autowired` on the fields. If you use the constructor then your application will fail fast at startup instead.
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Code2care
code2care.org › home › java › [fix] nullpointerexception cannot invoke findbyid because repository is null - java spring
[fix] NullPointerException Cannot Invoke findById because Repository is null - Java Spring | Code2care
January 26, 2026 - Servlet.service() for servlet ... 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....
Top answer
1 of 2
5

The solution is simple. You mocked a class customerDataRepository but did not instruct it the mock what to do if the corresponding method is called. Mockito mocks then default back on doing nothing by method call and if there is a return value return null. Since your returned customerData is null you get your NPE when calling on this object. In your case this is in the error case that you get by calling getCustomerId().

To solve this issue simply instruct your mock

@Test
void removeCustomerDataWhenConsentIsNotGiven() {
   CustomerData customerDataTest = customerData;
   //when
   Mockito.when(customerDataRepository.findCustomerByDialogId(Mockito.any())).thenReturn(new CustomerData()); // <-- Add this line
   customerDataService.giveConsent(false,22L);
   //then 
   verify(customerDataRepository,times(1)).save(customerDataTest);
}

you can obviously replace Mockito.any() with Mockito.anyInt() or 42 and new CustomerData() with a object you previously created. I think you get the idea ;)

2 of 2
1

Assuming that you have just corrected method names before posting it to Stackoverflow, and method you are calling in the test: giveConsent is, actually, the same method as methodTotest of the CustomerDataService.

Before calling customerDataService.giveConsent(false,22L);, you need to configure you repository to return some test (not null! or mocked) customerData entity:

when(customerDataRepository.findCustomerByDialogId(22L)).thenReturn(customerDataTest);
customerDataService.giveConsent(false,22L);

Note: since you are passing false as 1st variable, you will get to this branch of code

    if (!consent) {  
      customerDataRepository.deleteById(customer.getCustomerId());
    }

And in the test you are expecting save() method to be called, so the test will fail.

🌐
OneUptime
oneuptime.com › home › blog › how to fix 'cannot invoke tostring() on null' errors
How to Fix 'Cannot invoke toString() on null' Errors
December 22, 2025 - NullPointerExceptions account for a significant portion of runtime errors in Java applications. Understanding why they occur and how to prevent them is essential for building robust applications. flowchart TD A[Method Call] --> B{Is Object Null?} B -->|No| C[Execute Method] B -->|Yes| D[NullPointerException] D --> E["Cannot invoke toString() because X is null"] subgraph Common Causes F[Uninitialized Variables] G[Missing Database Records] H[Null API Responses] I[Missing Config Values] end
🌐
Apache Bugzilla
bz.apache.org › bugzilla › show_bug.cgi
NullPointerException when resolving webapp JARs as ...
Please note that by logging in/creating an account here, you: Understand that projects developed at the Apache Software Foundation are licensed under the terms and conditions of the Apache License version 2.0. Have read and understand the terms and conditions of the Apache License version 2.0. ...