gpt4 book ai didi

java - 为什么 Spring 无法实例化我的自定义 ApplicationContext?

转载 作者:行者123 更新时间:2023-11-30 01:55:17 25 4
gpt4 key购买 nike

这是我的代码,缩减为最小可重现的情况:

@SpringBootApplication
@public class IfserverApplication {

private class AppContext extends AnnotationConfigServletWebServerApplicationContext {
}

public static void main(String[] args) {
new Configurator("IFServer");
try {
SpringApplication app = new SpringApplication(IfserverApplication.class);
app.setApplicationContextClass(AppContext.class);
app.run(args);
} catch (Throwable e) {
e.printStackTrace();
}
}

}

这是我收到的错误:

Caused by: java.lang.NoSuchMethodException: com.inlet.ifserver.IfserverApplication$AppContext.<init>()
at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_192]
at java.lang.Class.getDeclaredConstructor(Class.java:2178) ~[na:1.8.0_192]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:122) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
... 3 common frames omitted

这似乎是说我的 AppContext 类没有默认构造函数。但是,当然,这就是它的全部。我尝试显式添加默认(无参数)构造函数,但这没有帮助,而且无论如何这是必要的,这是没有意义的。

我想有人可能只需查看我的代码就可以告诉我出了什么问题,但我认为通过使用调试器进一步挖掘来提供我所看到的内容不会有什么坏处......

我已经调试到代码失败的地方。这是代码片段:

try {
return instantiateClass(clazz.getDeclaredConstructor());
} catch (NoSuchMethodException var3) {
Constructor<T> ctor = findPrimaryConstructor(clazz);
if (ctor != null) {
return instantiateClass(ctor);
} else {
throw new BeanInstantiationException(clazz, "No default constructor found", var3);
}
} catch (LinkageError var4) {
throw new BeanInstantiationException(clazz, "Unresolvable class definition", var4);
}

尝试查找构造函数时会命中第一个 catch block 。这是奇怪的一点。它不会失败,因为对“clazz.getDeclaredConstructor”的调用引发了异常。它似乎失败了,因为“clazz.getDeclaredConstructor”方法不存在!啊? 'clazz' 是一个 java.lang.Class 对象。显然应该有这个方法。

enter image description here

是否可能只是该方法是内置 C 方法或其他方法,而我的 IntelliJ 调试器看不到它?

假设我的调试器只是感到困惑,为什么这段代码无法通过查找它应该具有的默认构造函数来实例化我的类?

最佳答案

尝试将AppContext设为静态

    private static class AppContext extends AnnotationConfigServletWebServerApplicationContext 

对于非静态内部类,存在对外部类的隐式引用。我相信这会导致创建一个与无参数签名不匹配的合成构造函数。

关于java - 为什么 Spring 无法实例化我的自定义 ApplicationContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54728085/

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