我想知道JVM在完成应用程序时会做什么。它是否运行System.exit()
以及System.exit()
和SystemExiter()
之间有什么不同?
答案 0 :(得分:2)
JVM关闭的确切方式在实现之间会有所不同。请记住,JVM不是用Java编写的,也不会调用System.exit()
来结束自己。
SystemExiter
是一个Spring接口,用于抽象对System.exit()
的调用。应用程序可以使用该接口而不是直接调用System.exit()
,允许在测试期间修改行为。如果一个类在测试期间调用System.exit()
,它将结束测试周期,因为JVM将关闭。例如:
public class SomeClass {
private SystemExiter exiter; // inject this or accept in constructor
public void someMethod() {
// ...
exiter.exit(1);
}
}
在生产系统中,您可以使用JvmSystemExiter
实现来实际关闭VM。在测试中,您可能会模拟SystemExiter
接口并检查是否已调用exit()
。