在调用类方法时,Spring依赖注入获得了NullPointErexception

时间:2013-09-11 15:02:35

标签: java spring dependency-injection nullpointerexception

我有以下Java类,它有一个由构造函数args注入的字段dao

public class FeatureFormationFromRaw {

    private MyDAOImpl dao;   //field to be injected from beam.xml

    public FeatureFormationFromRaw(MyDAOImpl dao) {
        //do a fresh clean and save all data, dependency injection by constructor args
        dao.removeAll();          //This is fine.
        dao.saveDataAll();        // This is fine.
    }


    public float calcuFeatures(String caseName) {

        List<JSONObject> rawData = dao.getData(caseName);    //This line throws NullPointException because dao=null here.
                .........
    }

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        FeatureFormationFromRaw featureForm = (FeatureFormationFromRaw) context.getBean("featureFormation");

        float value = featureForm.calcuFeatures("000034");

    }

}

bean配置文件bean.xml通过构造函数args将MyDAOImpl对象注入到类中:

    <bean id="featureFormation" class="com.example.FeatureFormationFromRaw">
        <constructor-arg ref="myDaoImpl" />
    </bean>

    <bean id="myDaoImpl" class="com.example.MyDAOImpl">
    </bean>

我调试了我的应用程序,发现当执行构造函数FeatureFormationFromRaw(MyDAOImpl dao)时,dao从Spring bean注入中获取正确的值。但是,当调用方法calcuFeatures()时,变量dao在第一行为空。这是为什么?为什么变量dao在构造函数调用后消失并变为空?

2 个答案:

答案 0 :(得分:5)

在你的构造函数中,如果传入了dao,你必须将dao分配给你的私有变量。否则你不能在其他任何地方打电话。

this.dao = dao;添加到构造函数中。

换句话说,当你在构造函数中调用dao.removeAll()时,这是有效的,因为它使用参数dao。但是当你在另一个方法中调用dao.getData()时,它会失败,因为它正在使用尚未初始化的private MyDAOImpl dao;。注入将它放入构造函数中,但不会将其放入私有变量中。你必须这样做。

答案 1 :(得分:1)

private MyDAOImpl dao;   //field to be injected from beam.xml

    public FeatureFormationFromRaw(MyDAOImpl dao) {
        //do a fresh clean and save all data, dependency injection by constructor args
        dao.removeAll();          //This is fine.
        dao.saveDataAll();        // This is fine.
    }

在您的构造函数中添加this.dao = dao; ..尚未分配,因此当您使用其他方法时,nullNPE结束