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

Koo*_*ark 25 java spring spring-mvc default-constructor

我不想为我的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
Run Code Online (Sandbox Code Playgroud)

这真的有必要吗?

nic*_*ild 29

不,您不需要使用默认(无arg)构造函数.

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

<bean id="AuditRecord" class="com.bartholem.AuditRecord"/>

<bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
  <property name="someProperty" val="someVal"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

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

<bean id="AnotherAuditRecord" class="com.bartholem.AuditRecord">
  <constructor-arg val="someVal"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

如果你想在你的应用程序上下文引用另一个bean中,你可以使用它做ref的属性constructor-arg元素,而不是val属性.

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

<bean id="AnotherBean" class="some.other.Class" />
Run Code Online (Sandbox Code Playgroud)


Rya*_*art 19

尼古拉斯的回答是关于XML配置的钱.我只想指出,在使用注释来配置bean时,不仅可以更简单地进行构造函数注入,这是一种更自然的方法:

class Foo {
    private SomeDependency someDependency;
    private OtherDependency otherDependency;

    @Autowired
    public Foo(SomeDependency someDependency, OtherDependency otherDependency) {
        this.someDependency = someDependency;
        this.otherDependency = otherDependency;
    }
}
Run Code Online (Sandbox Code Playgroud)


hvg*_*des 1

您也许可以进行基于构造函数的注入,即类似这样的操作(取自此处的文档)

<bean id="foo" class="x.y.Foo">
    <constructor-arg ref="bar"/>
    <constructor-arg ref="baz"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

但我不确定它会起作用。

如果您正在定义 JavaBean,则需要遵循约定并在其上放置一个公共的无参数构造函数。