微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用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:创建类路径资源[spring-config.xml]中定义名为’InnerBean’的bean时出错:bean的实例化失败;嵌套异常是org.springframework.beans.BeanInstantiationException:无法实例化bean类[com.springexample.ExampleBean $InnerBean]:找不到认构造函数;嵌套异常是java.lang.NoSuchMethodException:com.springexample.ExampleBean $InnerBean.()

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

谁能帮我?

最佳答案
这是Java的一个警告 – 内部类认构造函数不是无参数构造函数.它们的认构造函数采用1个类型的参数 – 外部类.

所以,使用< constructor-arg>传递ExampleBean类型的bean

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐