注意:这旨在成为常见问题的规范答案。我有一个 Spring @Service 类(MileageFeeCalculator),它有一个 @Autowired 字段(rateService),但是当我...时该字段为空...
注意:这旨在成为常见问题的规范答案。
我有一个 Spring @Service
类 ( MileageFeeCalculator
),它有一个 @Autowired
字段 ( rateService
),但是 null
当我尝试使用它时,该字段是。日志显示 bean MileageFeeCalculator
和 MileageRateService
每当我尝试调用 NullPointerException
,我都会得到一个 mileageCharge
。为什么 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
但实际上没有自动装配的服务 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)
...