Matin Kh
Matin Kh

Reputation: 5178

Spring: Calling parent's method, gives null point exception and gets correct in a strage way

I have a class BaseResource.java as follows:

public class BaseResource{

    protected UserManager userManager;
    public void doSth(){
        Object obj = userManager.returnObject(); //This is where exception is thrown
    }
    public UserManager getUserManager() {
        return userManager;
    }
    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }
}

You can see the setter, right? This BaseResource has a child CustomerResurce.java:

public class CommonResources extends BaseResource{
    private UserManager userManager;
    public void doSthElse(){
         Object obj = doSth(); // Calling its parent's method
         //Other stuff
    }
    public UserManager getUserManager() {
        return userManager;
    }
    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }
}

When there is UserManager in the child's class and calling parent's method, JavaNullPointException rises. But as I remove the

private UserManager usermanager;

(and its getter and setter) from the child's class, the problem is solved! Why is that?

And this is my Spring Configuration:

<bean id="baseResource" class="com.datx.web.resources.core.BaseResource"
    scope="session" autowire="byName" />
<bean id="customerResources" class="com.datx.web.resources.core.CustomerResources"
    scope="session" autowire="byName" />
<bean id="userManager" class="com.datx.usermanagement.manager.UserManager"
    autowire="byName" scope="prototype"/>

Upvotes: 0

Views: 1474

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340933

Private userManager field shadows protected userManager field in base class. Essentially you have two variables now - one visible in base class and another in subclass. Spring uses CommonResources.setUserManager() method overriding BaseResource.setUserManager(). Overriden version uses closest (private) userManager field.

Once you remove that field, the compiler will use protected field from base class. Basically this is how Java works, Spring has nothing to do here. To avoid such problems in the future, keep all your fields private and avoid overriding setters.

See also

Upvotes: 1

Related Questions