Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failing to create Innerbean using Spring - BeanInstantiationException No default constructor found

Tags:

java

spring

I started learning spring from Spring reference 3.0 and i wanted to try how to instantiate inner bean:

Here is my code:

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;
  }

 }


}

And my config file is:

When i am trying to retrieve the bean InnerBean i am getting the following error:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'InnerBean' defined in class path resource [spring-config.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.springexample.ExampleBean$InnerBean]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.springexample.ExampleBean$InnerBean.()

What could be the problem? I tried adding no-argument constructor in the InnerBean still i am getting error..

Can any one help me?

like image 605
javanoob Avatar asked Jul 10 '10 17:07

javanoob


2 Answers

That's one caveat of Java - inner classes default constructor isn't a no-arg constructor. Their default constructor takes 1 parameter of type - the outer class.

So, use <constructor-arg> to pass a bean of type ExampleBean

Of course, use non-static inner classes only if this is necessary. If the class is only what you have shown, then make it static. Or move it to a new file. Then you won't have the above restriction. Preferring static inner classes is a good practice not only for spring beans, but in Java in general.

like image 153
Bozho Avatar answered Oct 19 '22 05:10

Bozho


You didn't include your Spring XML file, but I don't think it matters.

It doesn't work because InnerBean is an inner class. It can't be instantiated this way because there would be no enclosing instance of ExampleBean. (Try doing new InnerBean() in Java and you'll see the problem.)

If an InnerBean instance doesn't need to be encapsulated inside an ExampleBean instance, you could make InnerBean static. Then you would be able to instantiate it using Spring. Or you could make InnerBean a top-level (i.e. non-nested) class.

See Nested Classes in the Java Tutorials if you need to know more about inner classes.

like image 37
Richard Fearn Avatar answered Oct 19 '22 05:10

Richard Fearn