bean class instantiation in spring for a class without default constructor

时光毁灭记忆、已成空白 提交于 2020-01-11 13:32:07

问题


I am using a third party library class XYZ as an argument in my model. XYZ does not have a default constructor. So spring is not able to create bean for it giving error message as

org.springframework.web.util.NestedServletException: Request processing failed; 

nested exception is org.springframework.data.mapping.model.MappingInstantiationException: 

Could not instantiate bean class [org.abc.def.XYZ]: No default constructor found;nested exception is java.lang.NoSuchMethodException: org.abc.def.XYZ./<init/>()
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:681)

What can I do to resolve this ? I can't add default constructor to XYZ.

I added the following in my dispatcher servlet, but it still don't works.

<bean name="token" class="org.abs.def.Xyx">
    <constructor-arg name="arg1" value="val1"/>
    <constructor-arg name="arg2" value="val2"/>
    <constructor-arg name="arg3" value="val3"/>
</bean>

Thanks.


回答1:


You can define it in the XML file as a spring bean passing all necessary parameters to instantiate it.

sample:

<bean id="xyz" class="com.a.b.Xyz" >
    <constructor-arg index="0" ref="anotherBean"/>
    <constructor-arg index="1" value="12"/> 
</bean>



回答2:


You'll need to provide <constructor-arg> elements in your application context config file, as described in the documentation.



来源:https://stackoverflow.com/questions/10649237/bean-class-instantiation-in-spring-for-a-class-without-default-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!