为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 Spring 不能实例化我的自定义 ApplicationContext?

为什么 Spring 不能实例化我的自定义 ApplicationContext?

收到一只叮咚 2022-06-23 18:01:25
这是我的代码减少到最小的可重现情况:@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 块。这是奇怪的一点。它没有失败,因为对 'clazz.getDeclaredConstructor' 的调用会引发异常。它似乎失败了,因为“clazz.getDeclaredConstructor”方法不存在!嗯?'clazz' 是一个 java.lang.Class 对象。它显然应该有这种方法。是否可能只是该方法是内置的 C 方法或其他东西,而我的 IntelliJ 调试器看不到它?假设我的调试器只是感到困惑,为什么这段代码无法通过查找它应该具有的默认构造函数来实例化我的类?
查看完整描述

1 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

尝试制作AppContext静态

    private static class AppContext extends AnnotationConfigServletWebServerApplicationContext

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


查看完整回答
反对 回复 2022-06-23
  • 1 回答
  • 0 关注
  • 109 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信