public class PropHolder {
  public static Properties prop;

  static {
    //code for loading properties from file
  }
}

// Referencing the class somewhere else:
Properties prop = PropHolder.prop;

propolder是我自己的一个类。类驻留在主类的同一个JAR文件中。所以这不应该,因为类路径中缺少任何JAR。

当我通过JAR tf myjarfile查看JAR文件时,我可以看到propolder .class列在那里。

顺便说一句:代码在我的本地机器上运行良好。但是当我将它与一些脚本一起部署到Linux服务器上时就无法工作了。所以我认为这不是代码的问题。 但出于某种原因。部署过程很难跟踪。

有什么问题吗?


当前回答

我遇到了同样的例外,这就是我解决问题的方法:

先决条件:

Junit类(和test),它扩展了另一个类。 ApplicationContext使用spring初始化,初始化项目。 应用程序上下文在@Before方法中初始化

解决方案:

从@BeforeClass方法初始化应用程序上下文,因为父类也需要一些在应用程序上下文中初始化的类。

希望这能有所帮助。

其他回答

Just several days ago, I met the same question just like yours. All code runs well on my local machine, but turns out error(noclassdeffound&initialize). So I post my solution, but I don't know why, I merely advance a possibility. I hope someone know will explain this.@John Vint Firstly, I'll show you my problem. My code has static variable and static block both. When I first met this problem, I tried John Vint's solution, and tried to catch the exception. However, I caught nothing. So I thought it is because the static variable(but now I know they are the same thing) and still found nothing. So, I try to find the difference between the linux machine and my computer. Then I found that this problem happens only when several threads run in one process(By the way, the linux machine has double cores and double processes). That means if there are two tasks(both uses the code which has static block or variables) run in the same process, it goes wrong, but if they run in different processes, both of them are ok. In the Linux machine, I use

mvn -U clean  test -Dtest=path 

为了运行一个任务,因为我的静态变量是要启动一个容器(或者可能初始化一个新的类加载器),所以它将一直保持到JVM停止,而JVM只有在一个进程中的所有任务停止时才会停止。每个任务都会启动一个新的容器(或类加载器),这会让jvm感到困惑。结果,错误发生了。 那么,如何解决呢?我的解决方案是向maven命令添加一个新命令,并使每个任务都转到相同的容器中。

-Dxxx.version=xxxxx #sorry can't post more

也许你已经解决了这个问题,但仍然希望它能帮助其他遇到同样问题的人。

我遇到了同样的例外,这就是我解决问题的方法:

先决条件:

Junit类(和test),它扩展了另一个类。 ApplicationContext使用spring初始化,初始化项目。 应用程序上下文在@Before方法中初始化

解决方案:

从@BeforeClass方法初始化应用程序上下文,因为父类也需要一些在应用程序上下文中初始化的类。

希望这能有所帮助。

添加这些import语句解决了这个问题:

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

我认为这里有个问题:

static {
    //code for loading properties from file
}

它会出现一些未捕获的异常,并传播到实际的ClassLoader,试图加载该类。不过,我们需要一个堆栈跟踪来确认这一点。

要么是这样,要么是在创建propolder时发生的。道具静态变量。

如上所述,这可能是许多事情。在我的情况下,我有一个静态初始化的变量,它依赖于我的属性文件中缺少的条目。将缺失的条目添加到属性文件中,问题就解决了。