เหตุใดฟิลด์ @Autowired ของฉันจึงเป็นโมฆะ
หมายเหตุ: นี่มีวัตถุประสงค์เพื่อเป็นคำตอบที่ยอมรับได้สำหรับปัญหาทั่วไป ฉันมี@ServiceคลาสSpring ( MileageFeeCalculator) ที่มี@Autowiredฟิลด์ ( rateService) แต่ฟิลด์นั้นคือnullเมื่อฉันพยายามใช้ บันทึกแสดงให้เห็นว่าทั้งMileageFeeCalculatorถั่วและMileageRateServiceถั่วกำลังถูกสร้างขึ้น แต่ฉันได้รับNullPointerExceptionเมื่อใดก็ตามที่ฉันพยายามที่จะเรียกmileageChargeวิธีการในบริการถั่วของฉัน เหตุใดสปริงจึงไม่ยอมฟิลด์ ชั้นควบคุม: @Controller public class MileageFeeController { @RequestMapping("/mileage/{miles}") @ResponseBody public float mileageFee(@PathVariable int miles) { MileageFeeCalculator calc = new MileageFeeCalculator(); return calc.mileageCharge(miles); } } ระดับบริการ: @Service public class MileageFeeCalculator { @Autowired private MileageRateService rateService; // <--- should be autowired, …