最佳答案
注意:这旨在成为一个常见问题的规范答案。
我有一个Spring@Service
类(MileageFeeCalculator
),它有一个@Autowired
字段(rateService
),但当我尝试使用它时该字段是null
。日志显示MileageFeeCalculator
bean和MileageRateService
bean都在创建中,但是每当我尝试在我的服务bean上调用mileageCharge
方法时,我都会得到一个NullPointerException
。为什么Spring没有自动装配字段?
控制器类:
@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, is null
public float mileageCharge(final int miles) {
return (miles * rateService.ratePerMile()); // <--- throws NPE
}
}
应该在MileageFeeCalculator
中自动编辑的Service bean,但它不是:
@Service
public class MileageRateService {
public float ratePerMile() {
return 0.565f;
}
}
当我尝试GET /mileage/3
时,我得到这个异常:
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)
...