我有一个Spring @Serviceclass(MileageFeeCalculator),它有一个@Autowiredfield(rateService),但该字段是null我尝试使用它时。日志显示正在创建MileageFeeCalculatorbean和MileageRateServicebean,但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
}
}
应该自动装配的服务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)
...
为什么我的Spring @Autowired字段为空?
Smart猫小萌
小唯快跑啊
慕标5832272