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