【问题标题】:Wildfly VFS - URLClassLoader is not able to load properties fileWildfly VFS - URLClassLoader 无法加载属性文件
【发布时间】:2018-04-10 19:31:24
【问题描述】:

我们在 Wildfly 上遇到了奇怪的问题(尽管它也发生在 Tomcat 上)。 在新的战争部署之后,我能够找到资源包文件,但是在执行一些代码(不确定是什么)之后,wildfly 无法使用 URLClassLoader 加载 ResourceBundle 文件。似乎是 ClassLoader 问题,但不确定。 我们如何确定它的罪魁祸首? 这是用于获取 ResourceBundle 的代码:

Locale locale = Locale.getDefault();
java.io.File fileObj = new java.io.File(bundleName);
java.net.URL resourceURL = null;

try {
    resourceURL = fileObj.getParentFile().toURI().toURL();
} catch (MalformedURLException e) {
    e.printStackTrace();
}

URLClassLoader urlLoader = new URLClassLoader(
    new java.net.URL[] {
        resourceURL
});
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle(
bundleName.substring(
bundleName.lastIndexOf(File.separator) + 1,
bundleName.lastIndexOf(".")), locale, urlLoader);
try {
    msg = bundle.getString(bundleMsg);
} catch (Exception e) {
    e.printStackTrace();
}
return msg;

【问题讨论】:

  • 资源包在哪里?以及您的查找代码在哪里?什么是部署?战争?
  • 资源包是war文件的一部分,但不在“WEB-INF”中。查找的代码在 WEB-INF/classes 文件夹内。
  • 战争文件在哪里?
  • 结构如下: - "query/resource_bundle" 与 "WEB-INF" 平行

标签: java wildfly urlclassloader


【解决方案1】:

您不能通过java.io.File 对象引用WAR 或JAR 文件中的任何 对象。 WAR 和 JAR 不包含“文件”。

此外,如果结构如您所说:

WAR
  WEB-INF
  query
      resource_bundle

那么你也不能作为类加载器资源访问它。

您必须使用javax.servlet.ServletContext.getResource(String path) 或javax.servlet.ServletContext.getResourceAsStream(String path) 访问此位置的资源。

只有 WEB-INF/classes 目录中的对象可以通过类加载器访问。

鉴于这些资源的性质,我认为您可能真的希望它们位于 WEB-INF/classes 下。如何执行此操作取决于您如何构建 Web 应用程序。如果您使用的是 Maven,那么正确的源位置将是 src/main/resources/query/resource_bundle。然后你可以使用:

 this.getClass().getResourceAsStream("/query/resource_bundle/" + bundleName);

如果我已经正确解释了您尝试做的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 2021-06-25
    • 2011-11-27
    • 2016-05-18
    相关资源
    最近更新 更多