小编典典

Spring是否要求所有bean具有默认构造函数?

spring

我不想为我的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

这真的有必要吗?


阅读 645

收藏
2020-04-21

共1个答案

小编典典

你是如何定义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中,你可以使用它做ref的属性constructor-arg元素,而不是val属性。

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

<bean id="AnotherBean" class="some.other.Class" />
2020-04-21