2

I've a weird problem of unable to instantiate a bean which is injected to another bean.

The PropertiesUtil is the bean in question. It's injected to the LoginController class as follows in my sn-servlet.xml

  <bean name="/Login.html" class="org.sn.auth.LoginController">
    <property name="dbUtil" ref="dbUtil"/>
    <property name="propertiesUtil" ref="propertiesUtil"/>
  </bean>

and my PropertiesUtil.java is

public class PropertiesUtil {

    private Properties properties;

    public PropertiesUtil() {
        properties = new Properties();
        try {            
                properties.load(ClassLoader.getSystemResourceAsStream(
                                    "/resources/messages.properties"));
        }
        catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}

And the NullPointerException occurs at the line where I try to use the properties to load a resource. I'm really confused why it's null when I'm clearly instanting it in the previous line.

I've also tried injecting the properties instance as a constructor-arg and also as a property from the sn-servlet.xml, but all in vain.

Is there something like I'm not supposed to do any operations in a constructor when that bean is spring-injected to some other class?

Thanks for any ideas!

asgs
  • 3,928
  • 6
  • 39
  • 54

1 Answers1

4

Check out the javadoc for ClassLoader.getResourceAsStream(). It returns null if the resource cannot be found. So it would seem that messages.properties cannot be found and the Properties.load() method will throw a NullPointerException when trying to read from a null InputStream.

krock
  • 28,904
  • 13
  • 79
  • 85
  • oh! I've placed it under WEB-INF/resources. What's the proper way to access it then? The NPE made me think that `properties` was actually getting null! – asgs Mar 12 '11 at 07:10
  • 2
    Check out [this question](http://stackoverflow.com/questions/793917/is-web-inf-in-the-classpath), WEB-INF is not on the classpath so the various `getResource..()` Methods will not be able to find it. Move the file to `WEB-INF/classes/resources/messages.properties` and you should be able to pick it up. – krock Mar 12 '11 at 07:19
  • dang! i just learnt a few days ago that `WEB-INF/classes` and `WEB-INF/lib` are in the classpath. Thanks a lot! – asgs Mar 12 '11 at 07:21