The issue you're facing is due to initialization of the following object

private final AtomicLong counter = new AtomicLong(dao.getLatestID());

You've Autowired the MessageBoxDAO dependency which is not initialized at the time of execution of the above instruction. Either you should initialize the counter after the completion of instantization process or use construction injection.

Answer from b.s on Stack Overflow
🌐
Coderanch
coderanch.com › t › 734114 › frameworks › Spring-Autowired-field-null
Why is my Spring @Autowired field null? (Spring forum at Coderanch)
September 1, 2020 - R Vicky wrote:@Rob, if I remove the static from @Autowired, it gives "Cannot make a static reference to the non-static field obj" You need to: * Create a Spring context. * Get an instance of MainClass from the context. * Access the instance's field. I'm not sure if your KeyLogger can actually be auto-wired. It's not a Spring bean, and even if it were, it does not have a constructor that Spring can call. For each bean constructor, Spring must be able to find proper values for the parameters. Either because they are annotated (e.g.
🌐
Marten Deinum
deinum.biz › 2020-07-03-Autowired-Field-Null
Why are my autowired fields null
Using the HelloWorldService below as a bean in a Spring application would fail. As there is no @Autowired (or @Inject or @Resource) on the field, Spring doesn’t know it needs to inject a dependency into the field. So the field remains null.
Discussions

Autowired object is null - java
I'm trying to autowire jdbctemplate in MessageBoxDAO class (which i guess is working fine), then i create autowired DAO object in the controller to get the latest ID in order to counter not getting More on stackoverflow.com
🌐 stackoverflow.com
java - Why is my Spring @Autowired field null? - Stack Overflow
Note: This is intended to be a canonical answer for a common problem. I have a Spring @Service class (MileageFeeCalculator) that has an @Autowired field (rateService), but the field is null when I ... More on stackoverflow.com
🌐 stackoverflow.com
java - Advice to track down cause of @Autowired being null - Stack Overflow
Looking through this question why-is-my-spring-autowired-field-null, it seems the most common reason why an @Autowired member object is null is because the containing class was created with "new& More on stackoverflow.com
🌐 stackoverflow.com
spring - con not invoke "" because this."" is null (or) Cannot invoke "CustomerRepository.findAll()" because "this.customerRepository" is null - Stack Overflow
Cannot invoke "com.saran.sprndatajpa.config.CustomerRepository.findAll()" because "this.customerRepository" is null ... This error occurs as the required bean is not autowired. More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 - java.lang.NullPointerException: null at com.baeldung.autowiring.service.MyService.serve(MyService.java:14) at com.baeldung.autowiring.controller.MyController.control(MyController.java:12)
🌐
More of Less
moreofless.co.uk › spring-mvc-java-autowired-component-null-repository-service
Two reasons why your Spring @Autowired component is null
@Controller public class Controller { @GetMapping("/example") public String example() { MyService my = new MyService(); my.doStuff(); } } @Service public class MyService() { @Autowired MyRepository repo; public void doStuff() { repo.findByName( "steve" ); } } @Repository public interface MyRepository extends CrudRepository<My, Long> { List<My> findByName( String name ); } This will throw a NullPointerException in the service class when it tries to access the MyRepository auto-wired Repository, not because there is anything wrong with the wiring of the Repository but because you instantiated MyService() manually with MyService my = new MyService().
Top answer
1 of 16
796

The field annotated @Autowired is null because Spring doesn't know about the copy of MileageFeeCalculator that you created with new and didn't know to autowire it.

The Spring Inversion of Control (IoC) container has three main logical components: a registry (called the ApplicationContext) of components (beans) that are available to be used by the application, a configurer system that injects objects' dependencies into them by matching up the dependencies with beans in the context, and a dependency solver that can look at a configuration of many different beans and determine how to instantiate and configure them in the necessary order.

The IoC container isn't magic, and it has no way of knowing about Java objects unless you somehow inform it of them. When you call new, the JVM instantiates a copy of the new object and hands it straight to you--it never goes through the configuration process. There are three ways that you can get your beans configured.

I have posted all of this code, using Spring Boot to launch, at this GitHub project; you can look at a full running project for each approach to see everything you need to make it work. Tag with the NullPointerException: nonworking

Inject your beans

The most preferable option is to let Spring autowire all of your beans; this requires the least amount of code and is the most maintainable. To make the autowiring work like you wanted, also autowire the MileageFeeCalculator like this:

@Controller
public class MileageFeeController {

    @Autowired
    private MileageFeeCalculator calc;

    @RequestMapping("/mileage/{miles}")
    @ResponseBody
    public float mileageFee(@PathVariable int miles) {
        return calc.mileageCharge(miles);
    }
}

If you need to create a new instance of your service object for different requests, you can still use injection by using the Spring bean scopes.

Tag that works by injecting the @MileageFeeCalculator service object: working-inject-bean

Use @Configurable

If you really need objects created with new to be autowired, you can use the Spring @Configurable annotation along with AspectJ compile-time weaving to inject your objects. This approach inserts code into your object's constructor that alerts Spring that it's being created so that Spring can configure the new instance. This requires a bit of configuration in your build (such as compiling with ajc) and turning on Spring's runtime configuration handlers (@EnableSpringConfigured with the JavaConfig syntax). This approach is used by the Roo Active Record system to allow new instances of your entities to get the necessary persistence information injected.

@Service
@Configurable
public class MileageFeeCalculator {

    @Autowired
    private MileageRateService rateService;

    public float mileageCharge(final int miles) {
        return (miles * rateService.ratePerMile());
    }
}

Tag that works by using @Configurable on the service object: working-configurable

Manual bean lookup: not recommended

This approach is suitable only for interfacing with legacy code in special situations. It is nearly always preferable to create a singleton adapter class that Spring can autowire and the legacy code can call, but it is possible to directly ask the Spring application context for a bean.

To do this, you need a class to which Spring can give a reference to the ApplicationContext object:

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;   
    }

    public static ApplicationContext getContext() {
        return context;
    }
}

Then your legacy code can call getContext() and retrieve the beans it needs:

@Controller
public class MileageFeeController {    
    @RequestMapping("/mileage/{miles}")
    @ResponseBody
    public float mileageFee(@PathVariable int miles) {
        MileageFeeCalculator calc = ApplicationContextHolder.getContext().getBean(MileageFeeCalculator.class);
        return calc.mileageCharge(miles);
    }
}

Tag that works by manually looking up the service object in the Spring context: working-manual-lookup

2 of 16
73

If you are not coding a web application, make sure your class in which @Autowiring is done is a spring bean. Typically, spring container won't be aware of the class which we might think of as a spring bean. We have to tell the Spring container about our spring classes.

This can be achieved by configuring in appln-contxt or the better way is to annotate class as @Component and please do not create the annotated class using new operator. Make sure you get it from Appln-context as below.

@Component
public class MyDemo {

    
    @Autowired
    private MyService  myService; 
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
            System.out.println("test");
            ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
            System.out.println("ctx>>"+ctx);
            
            Customer c1=null;
            MyDemo myDemo=ctx.getBean(MyDemo.class);
            System.out.println(myDemo);
            myDemo.callService(ctx);
            
            
    }

    public void callService(ApplicationContext ctx) {
        // TODO Auto-generated method stub
        System.out.println("---callService---");
        System.out.println(myService);
        myService.callMydao();
        
    }

}
🌐
GitHub
github.com › spockframework › spock › issues › 337
Grails - Cannot invoke method autowire() on null object · Issue #337 · spockframework/spock
August 30, 2015 - I have the following simple Integration spec that is throwing an NPE when executed: import grails.plugin.spock.IntegrationSpec class MyServiceIntegrationSpec extends IntegrationSpec { def "a true test"(){ expect: true } } Stacktrace: Cannot invoke method autowire() on null object java.lang.NullPointerException: Cannot invoke method autowire() on null object at grails.plugin.spock.IntegrationSpec.setupSpec(IntegrationSpec.groovy:47) Command: 'grails test-app :spock' Grails plugin: spock 0.6-SNAPSHOT Grails version: 2.0.0.M2 ·
Author: spockframework
🌐
Stack Overflow
stackoverflow.com › questions › 72735404 › advice-to-track-down-cause-of-autowired-being-null
java - Advice to track down cause of @Autowired being null - Stack Overflow
Looking through this question why-is-my-spring-autowired-field-null, it seems the most common reason why an @Autowired member object is null is because the containing class was created with "new&
Find elsewhere
🌐
Coderanch
coderanch.com › t › 706871 › frameworks › java-lang-NullPointerException-null-AutoWiring
java.lang.NullPointerException: null on AutoWiring a bean with AnnotationConfigApplicationContext (Spring forum at Coderanch)
Can you show the call to importDoc that causes the NullPointerException? Can you also show where in that class (the one calling importDoc) that the instance of Good it uses comes from? For example: Yes, Sure we are missing track. But importDoc is a public method available inside Good class so we don't need create an instance. But inside importDoc, we are trying use a bean or instance that is created by AnnotationConfigApplicationContext and here is where we're getting NPE only if I use Autowired but able to use the bean if I get through Context i.e getBean(RxxxDyyyyHelper.class).
🌐
W3Docs
w3docs.com › java
Why is my Spring @Autowired field null?
The field is being accessed before it has been injected. @Autowired fields are injected by the Spring container after the bean has been constructed, so make sure that you are not accessing the field before it has been injected.
🌐
Stack Overflow
stackoverflow.com › questions › 77877345 › autowired-beans-nested-in-a-request-controller-are-null
spring - Autowired Beans (Nested) in a Request Controller are Null - Stack Overflow
@PostConstruct public void init() { if(applicationContext !=null) { applicationContext.getAutowireCapableBeanFactory().autowireBean(this); } } I had similar autowiring NPE issues while invoking any service using it's constructor. ... It cannot be null else your application wouldn't even start.
🌐
Stack Overflow
stackoverflow.com › questions › 78111807 › autowired-class-is-null-in-testclassmockito
java - Autowired class is null in TestClassMockito - Stack Overflow
@Service @RequiredArgsConstructor public class CartService { private final CartRepository cartRepository; private final ProductRepository productRepository; private final CartItemRepository cartItemRepository; @Autowired private UserService userService; java.lang.NullPointerException: Cannot invoke "onlineshop.shop.service.UserService.getUserOfPrincipal(java.security.Principal)" because "this.userService" is null
🌐
GitHub
github.com › j-easy › easy-rules › issues › 51
@Autowired class is null inside Rule class · Issue #51 · j-easy/easy-rules
April 18, 2017 - @SpringRule public class Rule1 { @Autowired private MyDAO myDAO; --> (is null during runtime) public Rule1 () { super(); } @Condition public boolean when() { if (condition) { return true; } return false; } @Action(order = 1) public void then() throws Exception { myDAO.update("test"); System.out.println("Waiting state success"); } }
Author: j-easy
🌐
Code2care
code2care.org › home › java › [fix] nullpointerexception cannot invoke findbyid because repository is null - java spring
[fix] NullPointerException Cannot Invoke findById because Repository is null - Java Spring | Code2care
January 26, 2026 - As it is not injected by the Spring IoC container, you get a NullPointerException when you try to do an operation over it Solution: Make sure you add @Autowired annotation above all your repositories in the Controller class, Example: @Autowired ...
Top answer
1 of 5
4

You're probably missing the @repository annotation on top of your repository class.

Another unrelated word of advice:

In your controller you use findAll and filter in java to keep only the ids. Then you go to the same repository and perform another query per user-id from above. This is a causing you to create multiple database calls which are one of the most expensive operations you can do, when you already have all your data from the first single query...

Also if you're only looking at the bottom part of the function you don't event need a query per each user-id (when you have a list of user ids as input), you can create a query that uses the 'in' convention and pass a list of user-ids to create a single db call.

2 of 5
1

First of all I would get rid of @Autowired ICustomerRepository customerRepository; in UserList class. It doesn't belong there. The counting of linked customers should be executed in ICustomerRepository and the result to be passed into UserList via the constructor.

e.g.

public class UserList {

    private  String id;
    private String email;
    private String userType;
    private String rolls;
    private String partner;
    private Long customersLinked; //better use Long instead of Integer
    private String position;
    private String status;


    // constructor takes the number of linked customers as parameter
    public UserList (Users user, Long customersLinked ) { 
        this.id = user.getId();
        this.email = user.getEmail();
        this.userType = user.getUserType();
        this.rolls = user.getRolls();
        this.partner = user.getPartner();
        this.customersLinked = customersLinked;
        this.position = user.getPosition();
        this.status =user.getStatus();
    }

    //Getter and Setter
}

and then create the count query in ICustomerRepository

e.g.

public interface ICustomerRepository extends MongoRepository<Customer, String> {
    //other methods

    Long countByLinkedUsersIn(String id); //not so sure if this query works in mongo
}

and finally in your controller

Optional<Users> user = this.usersRepository.findById(userId);
Long count = this.usersRepository.countByLinkedUsersIn(userId);
userList.add(new UserList(user.get(), count));

P.S. I have a doubt for the query method: Long countByLinkedUsersIn(String id);. Usually when repository methods have "In" in their names, countByLinkedUsersIn, then it is expected as parameter a List and not a single user id. However if your previous method List<Customer> findAllByLinkedUsersIn(String id); worked for you, then this one should work too.

🌐
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();
    }
}
🌐
ConcretePage
concretepage.com › spring-boot › spring-boot-autowired-field-null-why
Spring Boot @Autowired Field Null - Why?
September 25, 2023 - Customer customer = new Customer(); In this case the object address will not be autowired and the value be null. This is because when we create object using new keyword in our code, it fails the dependency injection.