我有以下 Java 类,它有一个由构造函数参数注入(inject)的字段 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
通过构造函数参数将 MyDAOImpl
对象注入(inject)到类中:
<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 注入(inject)中获取正确的值。但是,当调用 calcuFeatures()
方法时,第一行变量 dao
为 null。这是为什么?为什么变量dao
在构造函数调用后消失并变为null?
最佳答案
在构造函数中,传入 dao 后,必须将 dao 分配给私有(private)变量。否则你无法在其他地方调用它。
将 this.dao = dao;
添加到您的构造函数中。
换句话说,当您在构造函数中调用 dao.removeAll()
时,它会起作用,因为它使用了参数 dao
。但是,当您在另一个方法中调用 dao.getData()
时,它会失败,因为它使用的是尚未初始化的 private MyDAOImpl dao;
。注入(inject)将其放入构造函数中,但不会将其放入私有(private)变量中。你必须这样做。
关于java - Spring依赖注入(inject)在调用其类方法时得到NullPointEException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18744769/