How to read properties file in web application? [duplicate]

Several notes:

  1. You should prefer the ClassLoader as returned by Thread#getContextClassLoader().

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    

    This returns the parentmost classloader which has access to all resources. The Class#getClassLoader() will only return the (child) classloader of the class in question which may not per se have access to the desired resource. It will always work in environments with a single classloader, but not always in environments with a complex hierarchy of classloaders like webapps.

  2. The /WEB-INF folder is not in the root of the classpath. The /WEB-INF/classes folder is. So you need to load the properties files relative to that.

    classLoader.getResourceAsStream("/auth.properties");
    

    If you opt for using the Thread#getContextClassLoader(), remove the leading /.

The JSF-specific ExternalContext#getResourceAsStream() which uses ServletContext#getResourceAsStream() “under the hoods” only returns resources from the webcontent (there where the /WEB-INF folder is sitting), not from the classpath.

Leave a Comment