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?
The compiler doesn't ever enforce the existence of a default constructor. You can have any kind of constructor as you wish. For some libraries or frameworks it might be necessary for a class to have a default constructor, but that is not enforced by the compiler.
What is the default constructor? Java doesn't require a constructor when we create a class. However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors.
Yes, Spring can invoke private constructors. If it finds a constructor with the right arguments, regardless of visibility, it will use reflection to set its constructor to be accessible.
Because there is no default constructor available in B, as the compiler error message indicates. Once you define a constructor in a class, the default constructor is not included. If you define *any* constructor, then you must define *all* constructors.
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With