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

laximzn5  于 2021-06-29  发布在  Java
关注(0)|答案(16)|浏览(385)

注:这是一个常见问题的标准答案。
我有一个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)
    ...
iqxoj9l9

iqxoj9l916#

我对spring还不熟悉,但我发现了这个有效的解决方案。请告诉我这是不是一条不可取的路。
我做Spring注射 applicationContext 在这个bean中:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils {

    public static ApplicationContext ctx;

    /**
     * Make Spring inject the application context
     * and save it on a static variable,
     * so that it can be accessed from any point in the application. 
     */
    @Autowired
    private void setApplicationContext(ApplicationContext applicationContext) {
        ctx = applicationContext;       
    }
}

如果需要,也可以将此代码放在主应用程序类中。
其他类可以这样使用它:

MyBean myBean = (MyBean)SpringUtils.ctx.getBean(MyBean.class);

通过这种方式,任何bean都可以由应用程序中的任何对象获得(也包括 new )以一种静态的方式。

相关问题