Posts

Showing posts from December 6, 2018

Why is my Spring @Autowired field null?

Image
up vote 470 down vote favorite 167 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 try to use it. The logs show that both the MileageFeeCalculator bean and the MileageRateService bean are being created, but I get a NullPointerException whenever I try to call the mileageCharge method on my service bean. Why isn't Spring autowiring the field? Controller class: @Controller public class MileageFeeController { @RequestMapping("/mileage/{miles}") @ResponseBody public float mileageFee(@PathVariable int miles) { MileageFeeCalculator calc = new MileageFeeCalculator(); return calc.mileageCharge(miles); } } Service class: