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 Overflow
Top answer
1 of 5
6

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);
    }    
}
2 of 5
1
 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.

Discussions

java - NullPointerException In Spring-boot and how do I fix it? - Stack Overflow
Today, I encountered a bug in my spring-boot project. In my code, I want to get the ApplicationContext, but it's null, so I couldn't use getBean(). More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Spring Boot project Null pointer Exception - Stack Overflow
I have gone through all the threads(16) posted about this Exception but none of them relate to my issue. I also have tried some answers from the following links with no luck! Spring security null p... More on stackoverflow.com
๐ŸŒ stackoverflow.com
February 14, 2019
rest - Spring Boot - Null Pointer Exception - Stack Overflow
Read the stack trace: "because "this.userService" is null". You didn't inject the user service into the REST controller properly. ... How to inject the user service in the REST Controller. Im a beginner to Spring boot More on stackoverflow.com
๐ŸŒ stackoverflow.com
July 11, 2023
java - Spring boot throwing null pointer exception while using Spring data JPA - Stack Overflow
I am a newbie to spring, when I am trying to save an entity to the database it is throwing a null pointer exception. Here is the relevant code for reference:- Here is the controller:- import com.pr... 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
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 75681023 โ€บ null-pointer-exception-on-invoking-a-service-in-a-spring-boot-application-when-j
Null pointer exception on invoking a service in a spring boot application when java-melody dependency is added - Stack Overflow
March 9, 2023 - java.lang.NullPointerException: null at com.java.corporate.service.impl.AuthenticationService.exceptionIfInvalidLogin(AuthenticationService.java:355) at com.java.corporate.service.impl.AuthenticationService.doSoftLogin(AuthenticationService.java:190) at com.java.corporate.service.impl.AuthenticationService$$FastClassBySpringCGLIB$$1d9d9fd9.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771) at org.springframework.aop.framework.ReflectiveMe
Top answer
1 of 2
2

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.

2 of 2
0

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
    }
}
Find elsewhere
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-lang-nullpointerexception
Java NullPointerException - Detect, Fix, and Best Practices | DigitalOcean
August 3, 2022 - Technical tutorials, Q&A, events โ€” This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
๐ŸŒ
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 - Key tool/command: Check the stack trace for null field access, then verify the class is Spring-managed (not new-instantiated). Watch out for: @Autowired on fields in classes created with new MyClass(). 2026 update: Spring Boot 4.0 / Spring Framework 7.0 (Nov 2025) adopt JSpecify @Nullable/@NullMarked annotations across the portfolio โ€” IntelliJ 2025.3+ and NullAway catch potential NPEs at compile time. [src9] Works with: Spring Boot 2.x-4.x, Spring Framework 5.x-7.x, Java 17+ (Boot 3.x/4.x baseline; Java 25 recommended for full JSpecify/NullAway).
๐ŸŒ
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();
    }
}
Top answer
1 of 1
4

A - How To Read Custom Property From application.properties In Spring Boot

A-1) Application Properties file

On of the default location of application.properties file is src/main/resources. Create this folder and also this file. Assuming your scenario, put the following properties inside application.properties file;

myconfig.ip=192.168.166.42
myconfig.port=8090

A-2) Configuration Class : AppConfig

In order to read the properties file, you need a class with @Configuration annotation. You need appropriate fields with @Value annotation for all the properties that you need to read. In addition, also you need the getter methods for these fields marked with @Value annotation. Please note that naming this class as "Configuration" is a very bad choice because there is also an annotation with the same name, thus I name it as "AppConfig"

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Value("${myconfig.ip}")
    private String ip;

    @Value("${myconfig.port}")
    private int port;

    public String getIp() {
        return ip;
    }

    public int getPort() {
        return port;
    }

}

A-3) Demo

Then you create a fields of this AppConfig class which is written above, and mark it with @Autowired annotation. Then you can read the properties files easily;

@RestController
@RequestMapping("/")
public class InputManagementController {

    @Autowired
    private AppConfig config;

    @RequestMapping("/test")
    public String test() {
        return String.format(
                "Configuration Parameters: Port: %s, Ip: %s", 
                config.getPort(),
                config.getIp()
        );
    }

}

A-4) Output

B - Solution To Problem

B-1) InputManagementController.java

@RestController
public class InputManagementController {

    @Autowired
    private AppConfig configuration;

    @Autowired
    private ElasticSearchInterface elasticSearchInterface;

    @GetMapping("/crawler/start")
    public String start() {
        try {

            System.out.println(configuration.getIp());
            es.getInputs();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "started";
    }
}

B-2) ElasticSearchInterface.java

@Component
public class ElasticSearchInterface {

    @Autowired
    private AppConfig configuration;

    public List<Map<String, Object>> getInputs() {
        System.out.println(configuration.getIp());

        return null;
    }

}

B-3) AppConfig.java

@Configuration
public class AppConfig {

    @Value("${myconfig.ip}")
    private String ip;

    @Value("${myconfig.port}")
    private int port;

    public String getIp() {
        return ip;
    }

    public int getPort() {
        return port;
    }

}
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ spring โ€บ spring @autowired field null โ€“ common causes and solutions
Spring @Autowired Field Null โ€“ Common Causes and Solutions | Baeldung
January 8, 2024 - Thus, the MyComponent instance inside the MyService object we created will remain null, causing the NullPointerException we get when we try to call a method on this object. To solve this problem, we have to make the MyService instance used in our controller a Spring-managed Bean.
๐ŸŒ
Java Guides
javaguides.net โ€บ 2019 โ€บ 07 โ€บ nullpointerexception-java-example.html
NullPointerException in Java
August 18, 2023 - In this article, we will learn what is NullPointerException, Why does it occur, practical example, and how to avoid and handle NullPointerException.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 75862995 โ€บ spring-boot-junit-testingtesting-service-layer-and-mapper-class-pass-null-point โ€บ 75863363
java - spring boot Junit testing:testing service layer and mapper class pass null pointer exception - Stack Overflow
The NPE usually occurs when an object reference is uninitialized or set to null, and the program attempts to access it. In this case, the "userMapper" object was not initialized or set to null in the "UserServiceImpl" class, causing the program to throw the NPE when calling the "addRequest...
Top answer
1 of 2
6

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:

  1. 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 failed

  2. Follow 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.

2 of 2
3

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