bean类实例化在spring中为没有默认构造函数的类
问题描述:
我使用第三方库类XYZ作为我的模型中的参数。 XYZ没有默认构造函数。所以spring不能创建bean给它错误消息
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)
我该如何解决?我不能添加默认构造函数到XYZ。
What can I do to resolve this ? I can't add default constructor to XYZ.
我在我的dispatcher servlet中添加了以下内容,但它仍然不起作用。
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>
谢谢。
答
您可以在XML文件中将其定义为spring bean,传递所有必要参数来实例化它。
You can define it in the XML file as a spring bean passing all necessary parameters to instantiate it.
示例:
<bean id="xyz" class="com.a.b.Xyz" >
<constructor-arg index="0" ref="anotherBean"/>
<constructor-arg index="1" value="12"/>
</bean>