我有以下 Java 类,它有一个dao
由构造函数 args 注入的字段:
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 配置文件通过构造函数 args 将对象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
在第一行为空。这是为什么?为什么dao
构造函数调用后变量消失并变为null?