I have the following Java class that has a field dao which is injected by constructor 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");
}
}
The bean configuration file bean.xml injects the MyDAOImpl object to the class via constructor args:
<bean id="featureFormation" class="com.example.FeatureFormationFromRaw">
<constructor-arg ref="myDaoImpl" />
</bean>
<bean id="myDaoImpl" class="com.example.MyDAOImpl">
</bean>
I debugged my application and found that when the constructor FeatureFormationFromRaw(MyDAOImpl dao) is executed, dao gets the proper value from Spring bean injection. However, when the method calcuFeatures() is called, the variable dao is null at the first line. Why is that? Why does the variable dao disappear and become null after constructor call?
MyDAOnot implementationsMyDAOImpl.MyDAOrather than the implementing classMyDAOImplin the constructor arg, but then I need to do a cast likethis.dao = (MyDAOImpl) dao. Is it always a good practice to use interface than implementing class in constructor args? Any guidelines on using interface vs. concrete class in Spring DI constructor args?