Is default constructor required in Spring injection?

autowired, constructor, dependency-injection, spring

Solution

Spring only "requires" a default constructor if you plan on instantiating it without any arguments.

for example, if your class is like this;

public class MyClass {

  private String something; 

  public MyClass(String something) {
    this.something = something;
  }

  public void setSomething(String something) {
    this.something = something;
  }

}

and you set it up in Spring like this;

<bean id="myClass" class="foo.bar.MyClass">
  <property name="something" value="hello"/>
</bean>

you're going to get an error. the reason is that Spring instantiates your class `new MyClass()` then tries to set call `setSomething(..)`.

so instead, the Spring xml should look like this;

<bean id="myClass" class="foo.bar.MyClass">
  <constructor-arg value="hello"/>
</bean>

so have a look at your `com.client.Module` and see how its configured in your Spring xml

Problem

I'm trying to inject a constructor that takes some arguments. After compiling Spring complains it couldn't find a default constructor (I haven't defined it) and throws BeanInstatiationException and NoSuchMethodException. After defining a default constructor the exceptions don't appear anymore, however my object is never initialized with the argument constructor, only the default one is called. Does Spring really require a default constructor in this case? And if yes, how can I make it use the argument constructor instead of the default one? This is how I wire everything: ``` public class Servlet { @Autowired private Module module; (code that uses module...) } @Component public class Module { public Module(String arg) {} ... } ``` Bean configuration: ``` <beans> <bean id="module" class="com.client.Module"> <constructor-arg type="java.lang.String" index="0"> <value>Text</value> </constructor-arg> </bean> ... </beans> ``` Stack trace: ``` WARNING: Could not get url for /javax/servlet/resources/j2ee_web_services_1_1.xsd ERROR initWebApplicationContext, Context initialization failed [tomcat:launch] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'module' defined in URL [...]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.client.Module]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.client.Module.<init>() ```

Original source