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.

🌐
Knowledgelib
https://knowledgelib.io › home › software › debugging › how to fix nullpointerexception in spring boot
How to Fix NullPointerException in Spring Boot | knowledgelib.io
May 17, 2026 - 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).
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
    }
}
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
🌐
Medium
https://medium.com › @vinodbokare0588 › no-more-nullpointerexception-a-spring-boot-4-story-7974ad67fbc0
No More NullPointerException: A Spring Boot 4 Story | by Vinodbokare | Medium
November 7, 2025 - Spring Boot 4 introduced something revolutionary: non-null by default. Instead of assuming everything might be null, you explicitly mark the exceptions. Here’s what happened when Vinod’s team made one simple change. They added a file called package-info.java to their com.translate_Idea_2_code.users package:
🌐
Reflectoring
https://reflectoring.io › spring-boot-null-safety-annotations
Protect Your Code from NullPointerExceptions with Spring's Null-Safety Annotations
January 31, 2022 - Since NullPointerException is a runtime exception, it would be hard to figure out such cases during code compilation. Java’s type system does not have a way to quickly eliminate the dangerous null object references. Luckily, Spring Framework offers some annotations to solve this exact problem. In this article, we will learn how to use these annotations to write null-safe code using Spring Boot...
Top answer
1 of 3
4

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();
 }
}
2 of 3
2

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.";
}
Find elsewhere
🌐
OneUptime
https://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 - Use Optional for values that might not exist, validate inputs at boundaries, use constructor injection with required dependencies, and return empty collections instead of null. Modern Java's helpful NPE messages make debugging easier, but prevention is better than cure.
🌐
DigitalOcean
https://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.
🌐
Baeldung
https://baeldung.com › home › spring › spring @autowired field null – common causes and solutions
Spring @Autowired Field Null – Common Causes and Solutions | Baeldung
January 8, 2024 - Learn about an error that would cause a NullPointerException when we unintentionally mix Spring injection with objects we create by calling their constructors.
🌐
Moments Log
https://momentslog.com › home › handling null pointer exceptions in spring boot applications
Handling Null Pointer Exceptions in Spring Boot Applications - Moments Log
December 22, 2024 - In conclusion, while Null Pointer Exceptions can be a nuisance in Spring Boot applications, adopting best practices such as using Optional, validating inputs, practicing defensive programming, utilizing static analysis tools, maintaining a consistent coding style, and implementing thorough testing can significantly reduce their occurrence.