如何使用Jboss7.1从Java代码中加载像图像这样的资源?
这曾经用于Jboss4:
this.getClass().getClassLoader().getResourceAsStream("/myapp/includes/images/image1.png");
现在返回null.
现在使用Jboss7在Java代码中加载资源的最佳做法是什么?
我做了一些测试:
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
解决方法:
作为JBoss社区wiki上的documented(不使用jboss-deployment-structure.xml文件):
>为配置文件创建模块(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>
>向模块添加属性:
jboss-as-7/
modules/
com/
yourcompany/
configuration/
main/
module.xml
settings.properties
other-settings.xm
>使用MANIFEST.MF条目将模块添加到CLASSPATH:
Manifest-Version: 1.0
Dependencies: com.mycompany.configuration
>从CLASSPATH加载属性文件:
InputStream settingsStream =
getClass().getClassLoader().getResourceAsStream("settings.properties");
我必须创建一个名为com / mycompany / main的模块文件夹,并在其中添加所有图像.因此,至少在JBOSS_HOME中,它位于WAR之外.然后我可以使用以下方式加载图像:
URL imgUrl = this.getClass().getClassLoader().getResource("myimage.jpg");