0

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"/>
Matin Kh
  • 5,192
  • 6
  • 53
  • 77

1 Answers1

1

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

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • So `userManager` should not be null in either case. But I'm receiving the exception that tells me `userManager` in the parent class is null. Which shouldn't be, as Spring has to instantiate an object from `UserManager` in the parent class. – Matin Kh Aug 16 '12 at 08:36