shailesh
shailesh

Reputation: 761

bean class instantiation in spring for a class without default constructor

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.

Upvotes: 0

Views: 4834

Answers (2)

fmucar
fmucar

Reputation: 14558

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>

Upvotes: 3

JB Nizet
JB Nizet

Reputation: 691973

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

Upvotes: 0

Related Questions