Does Spring require all beans to have a default constructor?

Koo Park picture Koo Park · Sep 21, 2011 · Viewed 48.5k times · Source

I don't want to create a default constructor for my auditRecord class.

But Spring seems to insist on it:

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'auditRecord' defined in ServletContext resource
[/WEB-INF/applicationContext.xml]: 
Instantiation of bean failed; 
nested exception is org.springframework.beans.BeanInstantiationException: 
Could not instantiate bean class [com.bartholem.AuditRecord]: 
No default constructor found; 
nested exception is 
java.security.PrivilegedActionException:
java.lang.NoSuchMethodException: 
com.bartholem.AuditRecord

Is this really necessary?

Answer

nicholas.hauschild picture nicholas.hauschild · Sep 21, 2011

No, you are not required to use default (no arg) constructors.

How did you define your bean? It sounds like you may have told Spring to instantiate your bean something like one of these:

<bean id="AuditRecord" class="com.bartholem.AuditRecord"/>

<bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
  <property name="someProperty" val="someVal"/>
</bean>

Where you did not provide a constructor argument. The previous will use default (or no arg) constructors. If you want to use a constructor that takes in arguments, you need to specify them with the constructor-arg element like so:

<bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
  <constructor-arg val="someVal"/>
</bean>

If you want to reference another bean in your application context, you can do it using the ref attribute of the constructor-arg element rather than the val attribute.

<bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
  <constructor-arg ref="AnotherBean"/>
</bean>

<bean id="AnotherBean" class="some.other.Class" />