Spring是否要求所有bean都有默认构造函数? [英] Does Spring require all beans to have a default constructor?

查看:962
本文介绍了Spring是否要求所有bean都有默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想为我的 auditRecord 类创建默认构造函数。

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

但是Spring似乎坚持:

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

这真的有必要吗?

推荐答案

不,你不是需要使用默认(无arg)构造函数。

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

你是如何定义bean的?听起来你可能告诉Spring将你的bean实例化为以下其中一种:

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>

你没有提供构造函数参数的地方。前一个将使用默认(或没有arg)构造函数。如果你想使用一个接受参数的构造函数,你需要用 constructor-arg 元素指定它们,如下所示:

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>

如果要在应用程序上下文中引用另一个bean,可以使用<$ c来完成$ c> ref constructor-arg 元素的属性,而不是 val 属性。

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" />

这篇关于Spring是否要求所有bean都有默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆