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.
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.
java - NullPointerException In Spring-boot and how do I fix it? - Stack Overflow
java - Spring Boot project Null pointer Exception - Stack Overflow
rest - Spring Boot - Null Pointer Exception - Stack Overflow
java - Spring boot throwing null pointer exception while using Spring data 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
}
}
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.
It is clearly due to the fact your
postRepository is not autowired. Spring cannot intantiate it by itself until you specify it with an annotation @Autowired, or personally instantiate it say in a @PostConstruct way.
Have a new Interface
public interface PostRepository extends JpaRepository<Post , Long>{
}
And in your sevice class.
@AutoWired
private PostRepository postRepository;
Have your packages like this. All packages should be within the directory of SpringBootApp package.

Hope this helps !!
You haven't initialized the postRepository in your PostService. Did you mean for it to be autowired?
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();
}
}@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;
You are most likely running on JDK 11 or higher. One of the libraries you use is javassist (probably as a dependency of the Spring framework). Version 3.22 is not compatible with JDK 11 and causes the error.
Either upgrade to javassist 3.24 (by upgrading to the newest Spring Boot version 2.2.4.RELEASE which has a dependency to it) or downgrade to JDK 8.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.3.RELEASE</version>
</parent>
As a tip for investigating Java error logs:
Locate the first error. In your case it's:
2019-04-02 22:27:38.143 ERROR 13892 --- [ restartedMain] o.s.boot.SpringApplication : Application run failedFollow the associated stack trace and go to the innermost exception, i.e.go the last
Caused by:before the next error starts. In your case it's:
Caused by: java.lang.NullPointerException: null
at javassist.util.proxy.SecurityActions.setAccessible(SecurityActions.java:103) ~[javassist-3.22.0-GA.jar:na]
at javassist.util.proxy.DefineClassHelper.toClass3(DefineClassHelper.java:151) ~[javassist-3.22.0-GA.jar:na]
That's the real cause that you want to investigate.
Thank you Codo :) I have found the answer just a few minutes before you posted the comment. It was a tricky problem for me. I have assumed that Null pointer Expception as caused by a missing getter/setter or missing Constructor. But when I have analyzed the error I have located this line:
"Caused by: org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister"
And a have made a reserach and find out that I need to add:
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.23.1-GA</version>
</dependency>
This dependency into my pom.xml file. And this problem is exactly what you have descibed above.
Thank you for your help and fast response :) I have learned something new this day
The problem is not related neither with Controller nor Service classes.
A not-null Authentication instance is successfully injected into the controller. Otherwise a NullPointerException would be thrown in the userService.getLoggedinUser(...) method at the moment it does auth.getName().
UserMapper might return null in two cases:
- The
Authentication.getName()'s method call returnsnull- Why? If
UserMapper.getUser(...)receives anullusername as argument, the query will try to match using that null. Then, unless one user hasnullas username, theUserMapperwill return null since the database returns an empty ResulSet.
- Why? If
- There's no user in database that matches the given username.
I hope it might help!
It might throw NullPointerException because Spring isn't able to inject Authentication object into getHomePage() method.
Is Authentication Object annotated with annotations like @Component, @Service, etc.. or some other stereotype annotation ?
