tonga
tonga

Reputation: 11961

Spring dependency injection got NullPointException when calling its class method

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?

Upvotes: 0

Views: 1468

Answers (2)

Jayaram
Jayaram

Reputation: 1725

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.
    }

add this.dao = dao; inside your constructor ..which has not be assigned so when you are using with other method that time its null so you end of with NPE

Upvotes: 1

Jacob Mattison
Jacob Mattison

Reputation: 51052

In your constructer, having had the dao passed in, you must assign the dao to your private variable. Otherwise you can't call it anywhere else.

add this.dao = dao; to your constructor.

In other words, when you call dao.removeAll() within the constructor, that works because it's using the parameter dao. But when you call dao.getData() in another method, it fails because it's using the private MyDAOImpl dao; which hasn't been initialized. The injection puts it into the constructor, but doesn't put it into the private variable. You have to do that.

Upvotes: 5

Related Questions