Spring是否要求所有bean都有默认构造函数?
我不想为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实例化为以下之一:
你没有提供构造函数参数的地方。 前一个将使用默认(或没有arg)构造函数。 如果要使用接受参数的构造函数,则需要使用constructor-arg
元素指定它们,如下所示:
如果要在应用程序上下文中引用另一个bean,可以使用constructor-arg
元素的ref
属性而不是val
属性来实现。
尼古拉斯对XML配置的回答是正确的。 我只想指出,当使用注释来配置bean时,不仅可以更简单地进行构造函数注入,这是一种更自然的方式:
class Foo { private SomeDependency someDependency; private OtherDependency otherDependency; @Autowired public Foo(SomeDependency someDependency, OtherDependency otherDependency) { this.someDependency = someDependency; this.otherDependency = otherDependency; } }
您可能能够进行基于构造函数的注入,即类似这样的东西(取自此处的文档)
但我不确定它会起作用。
如果要定义JavaBean,则需要遵循约定并在其上放置一个公共的无参数构造函数。