gpt4 book ai didi

java - 如何让 NoClassDefFoundError 在编译阶段暴露

转载 作者:行者123 更新时间:2023-12-01 09:29:44 26 4
gpt4 key购买 nike

最近我在生产环境中遇到了一个bug,即当用户访问某些优惠券列表页面时,出现以下错误

java.lang.NoClassDefFoundError: com/myapp/common/util/WrappedBeanCopier

而maven依赖是这样的

myapp
- coupon
- common 2.0
- common 1.0

WrappedBeanCopier仅在common 2.0中使用,而myapp实际使用的是common 1.0,所以导致了这次事故的发生。

我想知道为什么可以成功编译部署到tomcat?有什么办法可以让它尽快暴露出来吗?例如编译失败。

最佳答案

不幸的是,在编译过程中获得有关 NoClassDefFoundError 错误的通知是不可能的。

原因是错误本身的存在就表明了这个错误:

(摘自 Exception 类的 javadoc)

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

所以对于这种错误确实没有 Elixir 。您可以采取的措施避免再次发生:

  • 使用 Maven 制定更可靠的依赖结构
  • 更彻底的测试(编译和生产之间应该有一个测试阶段、环境等)
  • 进行更多测试,因为此错误不仅会在类定义更改时发生,而且如果您的类在初始化静态变量时由于异常而无法加载,您也可能会遇到 NoClassDefFoundErrors 的困难。

永远不会加载的类的示例:

private static Integer someThresholdValue = MyClass.calculateThreshold();

private static Integer calculateThreshold() {
throw new Exception("some error occured");
}

注意:当上面的错误不经常发生时,它可能会变得 super 讨厌,但前提是该类试图在应用程序的启动序列的早期加载,假设 Spring 上下文尚未准备好......因此,每次您太急于测试时,您都会收到 NoClassDefFoundError,但如果您在访问 Web 应用程序之前等待 10 秒,那么一切都很好...不好的记忆。

关于java - 如何让 NoClassDefFoundError 在编译阶段暴露,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39544279/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com