Pierre Pierre - 4 months ago 58
Java Question

Load Resource returns null with Jboss7

How do I load resources like images from the java code with Jboss7.1?

This used to work with Jboss4:

this.getClass().getClassLoader().getResourceAsStream("/myapp/includes/images/image1.png");


Now this returns null.

What is best practice for loading resources in java code now with Jboss7?

I did some testing:

URL url = this.getClass().getResource("");
System.out.println(url);
url = this.getClass().getResource("../../../");
System.out.println(url);
url = this.getClass().getResource("../../../../");
System.out.println(url);
url = this.getClass().getResource("../../../../../");
System.out.println(url);
url = this.getClass().getResource("includes");
System.out.println(url);

13:33:49,143 INFO [stdout] (http--127.0.0.1-8080-1) vfs:/C:/Eclipse/apps/jboss-as-7.1.1.Final/standalone/deployments/my-ea.ear/my-web.war/WEB-INF/classes/com/xxx/yyy/beans/jsf/
13:33:49,144 INFO [stdout] (http--127.0.0.1-8080-1) vfs:/C:/Eclipse/apps/jboss-as-7.1.1.Final/standalone/deployments/my-ea.ear/my-web.war/WEB-INF/classes/com/xxx/
13:33:49,150 INFO [stdout] (http--127.0.0.1-8080-1) jar:file:/C:/Eclipse/apps/jboss-as-7.1.1.Final/modules/javax/activation/api/main/activation-1.1.1.jar!/com/
13:33:49,151 INFO [stdout] (http--127.0.0.1-8080-1) file:/C:/Eclipse/apps/jboss-as-7.1.1.Final/modules/sun/jdk/main/service-loader-resources/
13:33:49,152 INFO [stdout] (http--127.0.0.1-8080-1) null

Answer

As documented on the JBoss community wiki (without using a jboss-deployment-structure.xml file):

  1. Create a module for the configuration file (jboss-as-7/modules/com/yourcompany/configuration/main/module.xml):
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="com.mycompany.configuration">
    <resources>
        <resource-root path="."/>
    </resources>
</module>
  1. Add properties to the module:
jboss-as-7/
   modules/
      com/
         yourcompany/
            configuration/
               main/
                 module.xml
                 settings.properties
                 other-settings.xm
  1. Add the module to the CLASSPATH using a MANIFEST.MF entry:
Manifest-Version: 1.0
Dependencies: com.mycompany.configuration
  1. Load a properties file from the CLASSPATH:
InputStream settingsStream = 
  getClass().getClassLoader().getResourceAsStream("settings.properties");

I had to create a module folder called com/mycompany/main and add all the images in there. So this sits outside the WAR at least though within JBOSS_HOME. Then I could load the image using:

URL imgUrl = this.getClass().getClassLoader().getResource("myimage.jpg");
Comments