On the analysis of the code snippet given, the null pointer exception occurred since your code doesn't ask the spring dependency injector to inject EmployerService as a dependency to EmployerController, so it doesn't inject the EmployerService bean class to the reference private EmployerService employerService; thus it is null in EmployerController. You can ask Spring Dependency Injector to inject dependency by adding @Autowire annotation private EmployerService service; refence in EmployerController
Update your EmployerService to the following will work
package io.javabrains;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import io.javabrains.Entity.Employer;
@RestController
public class EmployerController {
//UPDATE : Autowiring
@Autowired
private EmployerService employerService;
@RequestMapping("/employer")
public List < Employer > getAllEmployers() {
return service.getAllEmployers();
}
/*
* @RequestMapping("/employer/{id}") public Employer getEmployer(@PathVariable
* int id) { return employerService.getEmployer(id); }
*/
@RequestMapping(method = RequestMethod.POST, value = "/employer/create")
public void addEmployer(@RequestBody Employer employer) {
employerService.addEmployer(employer);
}
}
And Also, the same issue would occur in Service when trying to access repository.
Update EmployeeService.java code include @autorwired logic:
package io.javabrains;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import io.javabrains.Entity.Employer;
@Service
public class EmployerService {
@Autowired
private Repository repository;
public List<Employer>getAllEmployers(){
List<Employer>employers = new ArrayList<>();
repository.findAll()
.forEach(employers::add);
return employers;
}
public void addEmployer(Employer employer) {
repository.save(employer);
}
}
Answer from SAMUEL on Stack OverflowOn the analysis of the code snippet given, the null pointer exception occurred since your code doesn't ask the spring dependency injector to inject EmployerService as a dependency to EmployerController, so it doesn't inject the EmployerService bean class to the reference private EmployerService employerService; thus it is null in EmployerController. You can ask Spring Dependency Injector to inject dependency by adding @Autowire annotation private EmployerService service; refence in EmployerController
Update your EmployerService to the following will work
package io.javabrains;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import io.javabrains.Entity.Employer;
@RestController
public class EmployerController {
//UPDATE : Autowiring
@Autowired
private EmployerService employerService;
@RequestMapping("/employer")
public List < Employer > getAllEmployers() {
return service.getAllEmployers();
}
/*
* @RequestMapping("/employer/{id}") public Employer getEmployer(@PathVariable
* int id) { return employerService.getEmployer(id); }
*/
@RequestMapping(method = RequestMethod.POST, value = "/employer/create")
public void addEmployer(@RequestBody Employer employer) {
employerService.addEmployer(employer);
}
}
And Also, the same issue would occur in Service when trying to access repository.
Update EmployeeService.java code include @autorwired logic:
package io.javabrains;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import io.javabrains.Entity.Employer;
@Service
public class EmployerService {
@Autowired
private Repository repository;
public List<Employer>getAllEmployers(){
List<Employer>employers = new ArrayList<>();
repository.findAll()
.forEach(employers::add);
return employers;
}
public void addEmployer(Employer employer) {
repository.save(employer);
}
}
private EmployerService employerService;
This mean you have created a reference variable of EmployerService not an object of EmployerService. Which can be done by using a new keyword. But as you know Spring Container uses DI(Dependency Injection) to manage a beans(an object, in above case object of EmployerService). So the object instantiation and whole lifecycle of an object is managed by the spring. For this we have to tell that the this object should be managed by the spring which is done by using @Autowired annotation.
Facing java.lang.NullPointerException in spring boot application - Stack Overflow
java - Spring Boot project Null pointer Exception - Stack Overflow
java.lang.NullPointerException on spring boot - Stack Overflow
java - Null pointer exception spring boot jpa - Stack Overflow
Spring Boot NullPointerException
How do I fix NullPointerException in Spring Boot?
NullPointerException Spring service
It would be good to have a separate class which implements ApplicationContextAware to provide application context to required classes. The problem here appears to be Spean bean life cycle and servlet container life cycle performing different operations.
i.e init can be called before context could be set by spring.
On line:
readHitchEventServletBean.setServlet(new ReadHitchEventServlet());
You are creating a new instance of the servlet object that is not a Spring Bean and thus it is not being wired-up correctly. If you want to do it this way, consider doing the following:
Application.java:
@Bean
public ServletRegistrationBean readHitchEventServletBean(ApplicationContext applicationContext) {
ServletRegistrationBean readHitchEventServletBean = new ServletRegistrationBean();
readHitchEventServletBean.setServlet(new ReadHitchEventServlet(applicationContext));
readHitchEventServletBean.setLoadOnStartup(5);
return readHitchEventServletBean;
}
ReadHitchEventServlet.java:
public class ReadHitchEventServlet extends HttpServlet {
private final ApplicationContext applicationContext;
ReadHitchEventServlet(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public void init() {
applicationContext.getBean("heheda");
}
}
Or even better would be to just leave out the ApplicationContext entirely and just wire the bean you ultimate want.
Application.java:
@Bean
public ServletRegistrationBean readHitchEventServletBean(Heheda heheda) {
ServletRegistrationBean readHitchEventServletBean = new ServletRegistrationBean();
readHitchEventServletBean.setServlet(new ReadHitchEventServlet(heheda));
readHitchEventServletBean.setLoadOnStartup(5);
return readHitchEventServletBean;
}
ReadHitchEventServlet.java:
public class ReadHitchEventServlet extends HttpServlet {
private final Heheda heheda;
ReadHitchEventServlet(Heheda heheda) {
this.heheda = heheda;
}
@Override
public void init() {
// do something with heheda
}
}
The repository is not injected.
In LoginController either create a constructor with your repositories (preferable way) or mark fields as @Autowired.
Check your LoginController class.
You have @Autowired only in StudentRepo, but the other 2 repos don't have such annotation. They won't be autowired and will be set as null by default.
Place @Autowired annotation there also, and check again.
Once you're using the new keyword, you're breaking all the injections used with @Autowired(it means that the MorningService and NightService will not be initialized) , that is why you're getting a NPE.
If you really want to test your mes() method from your controller, implement in your @SpringBootApplication class the CommandLineRunner interface.
Then you can inject a GenerateMessage bean with @Autowired and test your method.
Here is an example:
@SpringBootApplication
public class MainApplication implements CommandLineRunner {
@Autowired
private GenerateMessage generateMessage;
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
generateMessage.mes();
}
}
You must not mix usage of new with Autowired.
Once you're using the new keyword, you're breaking all the injections used with @Autowired(it means that the MorningService and NightService will not be initialized) , that is why you're getting a NPE.
Soulution No.1
use AUTOWIRE
@Autowired
public MorningService ms;
@Autowired
public NightService ns;
@Autowired
GenerateMessage gm;
@RequestMapping(path = "/test")
public String starter(){
// GenerateMessage gm=new GenerateMessage();
ns.mesage(); // this call working fine
gm.mes();
return "Mail scheduled.";
}
Solution No.2
use this keyword
@RequestMapping(path = "/test")
public String starter(){
// GenerateMessage gm=new GenerateMessage();
ns.mesage(); // this call working fine
this.mes();
return "Mail scheduled.";
}
@Autowired
private AlertRepository alertRepository;
and On your main application class add @EnableAutoConfiguration
@SpringBootApplication
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Also if you are not using @Repository then spring will never create bean for your repo, In that case it will throw nullPointer exception
@Repository
public interface AlertRepository extends
JpaRepository<Alert, Integer>{ }
Can you try doing these two points
- Have you added @EnableJpaRepositories annotation or xml configuration to enable Spring-data repository support.
Xml configuration like -
<jpa:repositories base-package="com.acme.repositories"/>.
2 I think you should remove static keyword from Repository Autowiring and make it private if it is used in only this clas, for instance
@Autowired
private AlertRepository alertRepository;
which version of spring boot do you use? If you're using old version of spring, then you need to create the constructor and add @Autowired above the constructor instead of using lombok annotation. Or you can change the lombok annotations like @AllArgsConstructor(onConstructor_ = @Autowired). Or just remove the lombok annoation and add @Autowired above userService.
Also make sure userService is a Spring Bean, check the annotation in UserService, it should have @Service or @Component or if it's created by @Bean method.
make sure you have an implementation of UserService marked as @Service. if you have it, then save all files and re-run the application.
1.you should add a @Component / @Service above CategoryService
2.you are not starting spring boot app correctly . you should do this instead of Demo1:
package library;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AccessingDataJpaApplication {
public static void main(String[] args) {
SpringApplication.run(AccessingDataJpaApplication.class, args);
}
}
more on this can be found in https://spring.io/guides/gs/accessing-data-jpa/
answering your question directly , the reason your are getting NPE is because categoryDao in CategoryService is null , since you are not starting spring boot correctly.
P.S
you should note that having your app class (AccessingDataJpaApplication ) in a package "higher" in the hierarchy(library package) then the rest of your components will make this work out of the book , otherwise you will have to mention the correct packages in the @SpringBootApplication annotation
First what you need to add is @SpringBootApplication to the main class. Second - SpringApplication.run(Demo1.class, args); at the first line of main(executable) method. And also, don't forget to add @Service to the service class of your application.
I did some modifications to your code.
The change that I did was in the StudentServiceImpl class. I removed the @Autowired annotation and did constructor injection.
@Service
public class StudentServiceImpl implements StudentService {
private final StudentRepository studentRepository;
public StudentServiceImpl(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
//others are same
}
And in the test class.
@RunWith(MockitoJUnitRunner.class)
public class StudentServiceImplTest {
private StudentService studentService;
private StudentRepository studentRepository;
@Test
public void findAll(){
studentRepository = mock(StudentRepository.class);
studentService = new StudentServiceImpl(studentRepository);
List<Student> studentList = new ArrayList<>();
studentList.add(new Student(1, "person1", "[email protected]"));
studentList.add(new Student(2, "person2", "[email protected]"));
when(studentRepository.findAll()).thenReturn(studentList);
List<Student> expectedList = studentService.findAl();
assertEquals(2, expectedList.size());
}
}
Now I can see the test passing.

Also, read this article which says "Get rid of @InjectMocks".
I hope it helps you :) Thanks a lot.
The mock you are configuring here:
StudentRepository studentRepository = mock(StudentRepository.class);
Is not injected into the service. Remove the initialisation of studentRepository inside your test and just use the one you have already annotated with @Mock.
The problem is with your request structure - with current code, you should use request structure as -
{
"ToDoDto" : {
"title": "exmple-1",
"description": "example-1",
"date": "2032-03-27",
"status": "pending",
"userDto": {
"id": 1
}
}
}
OR change this code stub -
@PostMapping("/todos")
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<ToDoResponse> addToDo(@RequestBody ToDoDto req) {
try {
ToDoResponse res = new ToDoResponse();
res.setToDoDto(toDoService.addToDo(req.getToDoDto()));
return ResponseEntity.ok(res);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
basically when you are doing req.getToDoDto() Its returning null, because of your request structure.
Your JSON object is named ToDoDto but it is mapped to toDoDto in your ToDoRequest class.
Assuming you are using Jackson for data-binding, you can annotate toDoDto defined in ToDoRequest with @JsonProperty to override the property name:
@JsonProperty("ToDoDto")
ToDoDto toDoDto;