无法使用Spring创建Innerbean – BeanInstantiationException找不到默认构造函数

我从Spring reference 3.0开始学习spring,我想尝试如何实例化内部bean:

这是我的代码:

package com.springexample; public class ExampleBean { private String samplePropertyExampleBean; public void setSamplePropertyExampleBean(String samplePropertyExampleBean) { this.samplePropertyExampleBean = samplePropertyExampleBean; } public String getSamplePropertyExampleBean() { return samplePropertyExampleBean; } class InnerBean{ private String sampleProperty; public void setSampleProperty(String sampleProperty) { this.sampleProperty = sampleProperty; } public String getSampleProperty() { return sampleProperty; } } } 

我的配置文件是:

当我试图检索bean InnerBean时,我收到以下错误:

线程“main”org.springframework.beans.factory.BeanCreationException中的exception:在类路径资源[spring-config.xml]中定义的名称为’InnerBean’的bean创建错误:bean的实例化失败; 嵌套exception是org.springframework.beans.BeanInstantiationException:无法实例化bean类[com.springexample.ExampleBean $ InnerBean]:找不到默认构造函数; 嵌套exception是java.lang.NoSuchMethodException:com.springexample.ExampleBean $ InnerBean。()

可能是什么问题呢? 我尝试在InnerBean中添加无参数构造函数仍然我收到错误..

谁能帮我?

这是Java的一个警告 – 内部类默认构造函数不是无参数构造函数。 它们的默认构造函数采用1个类型的参数 – 外部类。

因此,使用传递ExampleBean类型的bean

当然,只有在必要时才使用非静态内部类。 如果该类仅是您所显示的类,则将其static 。 或者将其移动到新文件。 那你就没有上述限制了。 首选静态内部类是一种很好的做法,不仅适用于spring bean,也适用于Java。

您没有包含Spring XML文件,但我认为这不重要。

它不起作用,因为InnerBean是一个内部类。 它不能以这种方式实例化,因为没有ExampleBean封闭实例。 (尝试在Java中使用new InnerBean() ,你会看到问题。)

如果不需要将ExampleBean实例封装在ExampleBean实例中,则可以使InnerBean静态。 然后你就可以使用Spring实例化它了。 或者你可以使InnerBean成为顶级(即非嵌套)类。

如果您需要了解有关内部类的更多信息,请参阅Java教程中的嵌套类 。