0

daoコンストラクター引数によって注入されるフィールドを持つ次の Java クラスがあります。

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注入します。MyDAOImpl

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

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

アプリケーションをデバッグしたところ、コンストラクターFeatureFormationFromRaw(MyDAOImpl dao)が実行されると、daoSpring Bean インジェクションから適切な値が取得されることがわかりました。ただし、メソッドcalcuFeatures()が呼び出されると、変数daoは最初の行で null になります。何故ですか?daoコンストラクターの呼び出し後に変数が消えて null になるのはなぜですか?

4

2 に答える 2

5

コンストラクターで、dao を渡した後、dao をプライベート変数に割り当てる必要があります。そうしないと、他の場所で呼び出すことはできません。

this.dao = dao;コンストラクターに追加します。

dao.removeAll()つまり、コンストラクター内で呼び出すと、パラメーターを使用しているため機能しますdao。しかしdao.getData()、別のメソッドを呼び出すと、初期化されていない を使用しているため失敗しprivate MyDAOImpl dao;ます。インジェクションはそれをコンストラクターに入れますが、プライベート変数には入れません。あなたはそれをしなければなりません。

于 2013-09-11T15:09:25.917 に答える
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;コンストラクター内に追加します..割り当てられていないため、他のメソッドを使用している場合は、そのnull時点で終了しますNPE

于 2013-09-11T15:13:10.307 に答える