Dlaczego moje pole Spring @Autowired jest zerowe?

Uwaga: ma to być kanoniczna odpowiedź na typowy problem.

Mam wiosnę@Service klasa (MileageFeeCalculator), który ma@Autowired pole (rateService), ale pole jestnull kiedy próbuję go użyć. Dzienniki pokazują, że zarównoMileageFeeCalculator fasola iMileageRateService fasola jest tworzona, ale dostajęNullPointerException ilekroć próbuję zadzwonić domileageCharge metoda na moim komponencie usługi. Dlaczego Spring nie zasila pola?

Klasa kontrolera:

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

Klasa usług:

@Service
public class MileageFeeCalculator {

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

    public float mileageCharge(final int miles) {
        return (miles * rateService.ratePerMile()); // <--- throws NPE
    }
}

Fasola serwisowa, która powinna zostać automatycznie włączonaMileageFeeCalculator ale to nie jest:

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

Kiedy próbujęGET /mileage/3, Dostaję ten wyjątek:

java.lang.NullPointerException: null
    at com.chrylis.example.spring_autowired_npe.MileageFeeCalculator.mileageCharge(MileageFeeCalculator.java:13)
    at com.chrylis.example.spring_autowired_npe.MileageFeeController.mileageFee(MileageFeeController.java:14)
    ...

questionAnswers(13)

yourAnswerToTheQuestion