加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

使用Spring无法创建Innerbean – BeanInstantiationException

发布时间:2020-12-15 01:26:05 所属栏目:大数据 来源:网络整理
导读:我从Spring reference 3.0开始学习spring,我想尝试如何实例化内部bean: 这是我的代码: package com.springexample;public class ExampleBean { private String samplePropertyExampleBean; public void setSamplePropertyExampleBean(String samplePropert

我从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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读