2011-09-20 97 views
24

我不想爲我的auditRecord類創建默認構造函數。Spring是否要求所有的bean都有默認的構造函數?

但春天似乎要堅持它:

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 

這真的有必要?

+0

請出示你的配置加載豆 - XML或註釋 – atrain

+0

https://stackoverflow.com/questions/25272543/no-default-constructor-found-nested-exception-is-java-lang-nosuchmethodexceptio – newday

回答

1

你也許可以做到基於構造函數的注入,即這樣的事情(從資料爲準發現here

<bean id="foo" class="x.y.Foo"> 
    <constructor-arg ref="bar"/> 
    <constructor-arg ref="baz"/> 
</bean> 

,但我不知道它會工作。

如果你正在定義一個JavaBean,你需要遵循約定並在其上放置一個公共的無參數構造函數。

28

不,您不需要使用默認(無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中,您可以在使用refconstructor-arg元素的屬性,而不是val屬性。

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

<bean id="AnotherBean" class="some.other.Class" /> 
18

nicholas對XML配置的回答是正確的。我只是想用註釋來配置你的bean時指出,它不僅是簡單的做構造函數注入,這是一個更自然的方式來做到這一點:

class Foo { 
    private SomeDependency someDependency; 
    private OtherDependency otherDependency; 

    @Autowired 
    public Foo(SomeDependency someDependency, OtherDependency otherDependency) { 
     this.someDependency = someDependency; 
     this.otherDependency = otherDependency; 
    } 
} 
+1

我有一個小問題。這個註解在應用程序的一部分中起作用,但是在測試中,我得到了'no no-argument constructor'錯誤。您能否告訴我們是否有辦法解決這個問題,而無需注入參數或添加默認構造函數? –

+0

@JohnDoe:你需要提出一個新的問題,而不是發表評論到一個非常古老的答案。此外,如果這就是你的問題,你不會得到一個好的答案。根據需要包含堆棧跟蹤和示例代碼以演示您的問題。參見[SSCCE](http://sscce.org/)。另見[如何問](http://stackoverflow.com/questions/how-to-ask)。 –

+0

你可能是對的,我會考慮創建帖子。 –

相關問題