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)
が実行されると、dao
Spring Bean インジェクションから適切な値が取得されることがわかりました。ただし、メソッドcalcuFeatures()
が呼び出されると、変数dao
は最初の行で null になります。何故ですか?dao
コンストラクターの呼び出し後に変数が消えて null になるのはなぜですか?