为什么我的spring@autowired字段为空?

8ehkhllq  于 2021-07-03  发布在  Java
关注(0)|答案(16)|浏览(406)

注:这是一个常见问题的标准答案。
我有一个Spring @Service 班级( MileageFeeCalculator )有一个 @Autowired 字段( rateService ),但这个领域 null 当我尝试使用它的时候。日志显示 MileageFeeCalculator 豆子和咖啡 MileageRateService 正在创建bean,但我得到一个 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
    }
}

应该自动连线的服务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)
    ...
jw5wzhpr

jw5wzhpr16#

另一个解决方案是打电话: SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this) 要像这样计算里程数:

@Service
public class MileageFeeCalculator {

    @Autowired
    private MileageRateService rateService; // <--- will be autowired when constructor is called

    public MileageFeeCalculator() {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this)
    }

    public float mileageCharge(final int miles) {
        return (miles * rateService.ratePerMile()); 
    }
}

相关问题