我不想为我的 auditRecord
类创建默认构造函数。
但Spring似乎坚持这样做:
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
真的有必要吗?
最佳答案
不,您不需要使用默认(无 arg)构造函数。
你是如何定义你的 bean 的?听起来您可能已经告诉 Spring 实例化您的 bean,如下所示:
<bean id="AuditRecord" class="com.bartholem.AuditRecord"/>
<bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
<property name="someProperty" val="someVal"/>
</bean>
您没有提供构造函数参数的地方。前一个将使用默认(或无 arg)构造函数。如果要使用接受参数的构造函数,则需要使用 constructor-arg
元素指定它们,如下所示:
<bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
<constructor-arg val="someVal"/>
</bean>
如果您想在应用程序上下文中引用另一个 bean,您可以使用 constructor-arg
元素的 ref
属性而不是 val
属性。
<bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
<constructor-arg ref="AnotherBean"/>
</bean>
<bean id="AnotherBean" class="some.other.Class" />
关于java - Spring 是否要求所有 bean 都具有默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7492652/