为什么我的 Spring @Autowired 字段为空?
注意:这是常见问题的规范答案。
我有一个Spring类()有一个字段(),但这个字段是当我尝试使用它时。日志显示正在创建 Bean 和 Bean,但是每当我尝试在我的服务 Bean 上调用该方法时,我都会得到一个。为什么Spring不自动布线?@Service
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, is null
public float mileageCharge(final int miles) {
return (miles * rateService.ratePerMile()); // <--- throws NPE
}
}
应该自动插入但它不是的服务 Bean:MileageFeeCalculator
@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)
...