Possible Reasons for @Autowired Field Null


Autowired annotation is used by the spring framework that marks a constructor, field, setter method, or config method as autowired by Spring’s dependency injection facilities. This is an alternative to the Inject annotation, adding required-vs-optional semantics. For more details read the official documentation Autowired (Spring Framework 5.3.22 API)

1- The first reason could be that you did not mark the autowiring class as component or autowiring class has no default constructor or constructor with unsatisfied injection beans.

2- The second reason cloud is in your code you are creating an object by yourself in one place and in another place you are auto wiring it, check below example.

Controller class

@Controller
public class FeeController {    
    @RequestMapping("/mileage/{miles}")
    @ResponseBody
    public float fee(@PathVariable int miles) {
        FeeCalculator calc = new FeeCalculator();
        return calc.charge(miles);
    }
}

Service Class

@Service
public class FeeCalculator {

    @Autowired
    private RateService rateService; // <--- should be autowired, is null

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

@Service
public class RateService {
    public float ratePerMile() {
        return 0.565f;
    }
}

In the above code, you should use either JVM-managed Objects or Spring-managed Object to invoke methods. from the above code in the controller class, a new object is created FeeCalculator calc = new FeeCalculator(); to call the service class which has an auto-wired object.

So you should change the controller class like this.

@Controller
public class FeeController { 
    @Autowired
    FeeCalculator calc;
    @RequestMapping("/mileage/{miles}")
    @ResponseBody
    public float fee(@PathVariable int miles) {
        return calc.charge(miles);
    }
}

3- Not declared autowiring class as @Bean

4- Fourth reason can be you might use incorrect import for @Autowire or @Inject

5- You can use Springbeanautowiring support in your service class

@Service
public class FeeCalculator {

    @Autowired
    private RateService rateService; // <--- will be autowired when constructor is called

    public FeeCalculator() {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
    }

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

6- One another reason can be that your package structure is messed up, to fix this you should use @ComponentScan(“packageToScan”) on the configuration class of your spring application to instruct the spring to scan.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.