在spring中注入內部類刑然,有可能會遇到如下異常信息:
No default constructor found;
nested exception is java.lang.NoSuchMethodException: xx.xxx.xx.xx外部類$xx內部類.<init>()
看樣子是說找不到構造函數(shù)钾埂,于是我把 無/全 參構造函數(shù) 都加上了搂根,可依舊報相同錯誤硝训。
于是我想响委,是不是Spring在注入內部類的時候比較特殊?百度一下窖梁,果然有坑赘风!
內部類注入方式一:添加內部類構造函數(shù)參數(shù)
我們遇到上面的錯誤是因為非靜態(tài)的內部類默認的構造函數(shù)有一個參數(shù),這個參數(shù)指向其外部類的實例纵刘,所以我們需要給此內部類的bean添加constructor-arg節(jié)點邀窃,并指向外部類即可,類似配置如下:
<bean class="xx.xx.外部類" id="外部類id">
<property name="hands">
<list>
<bean class="xx.xx.外部類$內部類">
<constructor-arg ref="外部類id"></constructor-arg>
<property name="內部類屬性1" value="**"/>
</bean>
</list>
</property>
</bean>
注意: 內部類的類名由外部類的全稱+$+內部類的名稱
內部類注入方式二:將內部類修改為static
在內部類名class 前加上static即可彰导。
聲明:
此文參考并摘抄一部分自:https://www.cnblogs.com/lichmama/p/5670185.html
如有侵犯蛔翅,請聯(lián)系作者刪除敲茄。