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).
Discussions

Facing java.lang.NullPointerException in spring boot application - Stack Overflow
I am trying to make Log In page using spring boot. I have three categories of user : Student, College , Company. When I check if user exist or not following code is working fine for Student but not 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
java.lang.NullPointerException on spring boot - Stack Overflow
i have created a simple java class in spring boot application. calling a method ns.mesage(); from two different methods but one is executed and another one throw an null pointer exception. package More on stackoverflow.com
๐ŸŒ stackoverflow.com
February 18, 2020
java - Null pointer exception spring boot jpa - Stack Overflow
I am trying to pass values to the persistence layer in a springboot application using jpa. However, each time I get a null pointer exception despite that I see that the object to be persisted is well More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 15, 2018
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
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
    }
}
๐ŸŒ
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...
Find elsewhere
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.";
}
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
Rollbar
https://rollbar.com โ€บ home โ€บ how to catch and fix nullpointerexception in java
How to Catch and Fix NullPointerException in Java
June 30, 2026 - NullPointerException is the most frequently thrown exception in Java applications, accounting for countless crashes.