bean定义中的constructor-arg和property [英] constructor-arg and property together in bean definition

查看:243
本文介绍了bean定义中的constructor-arg和property的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<bean id="cObject" scope="request" class="x.y.z.CClass"/>
<bean id="bObject" scope="request" class="x.y.z.BClass"/>
<bean id="aObject" scope="request" class="x.y.z.AClass">
    <constructor-arg ref="bObject" />
    <property name="cRef" ref="cObject" />
</bean>

aObject.cRef由于某种原因未设置.注意,constructor-arg和property在相同的定义中使用.我还没有看到具有类似功能的示例/帖子.

aObject.cRef is not getting set for some reason. Note that constructor-arg and property are used in the same definition. I have not seen an example / post with similar feature.

推荐答案

在同一资源上,我的同事发现:

On same sources my colleague discover:

Caused by: org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name 'service.MenuService#0'
  defined in class path resource [spring-beans/integrator.xml]:
  Could not resolve matching constructor (hint: specify index/type/name
  arguments for simple parameters to avoid type ambiguities)

在我的主机,测试服务器和生产服务器上没有此类错误.

while my host, test and production servers have no such error.

使用:

<bean class="service.MenuService">
    <constructor-arg index="0" type="java.lang.String" value="#{user}"/>
    <constructor-arg index="1" type="java.lang.String" value="#{password}"/>
    <constructor-arg index="2" type="java.lang.String" value="#{uri}"/>
    <property name="system" value="OPRT"/>
    <property name="client" value="OPRT"/>
</bean>

而bean中只有一个3-args构造函数.

while there are only one 3-args constructor in bean.

使用构造函数的原因-它通过调用init()方法在非Spring库上执行一些其他操作.并将args设置为字段.

The reason to use constructor - it perform some additional actions on non-Spring library by invoking init() method. And set args as fields.

所以我将spring-beans.xml更改为:

<bean class="service.MenuService" init-method="init">
    <property name="login" value="#{user}"/>
    <property name="password" value="#{password}"/>
    <property name="httpsUrl" value="#{uri}"/>
    <property name="system" value="OPRT" />
    <property name="client" value="OPRT" />
</bean>

注意init-method=部分.

更新毕竟,我编写了简单的XML配置并在调试器中逐步了解Spring源代码.似乎在Spring 3.x中,可以在XML bean 定义中组合 constructor-arg 属性(请检查 doCreateBean >在AbstractAutowireCapableBeanFactory.java中,然后调用 createBeanInstance populateBean .)

UPDATE After all I wrote simple XML config and step through Spring source code in debugger. Seems that with Spring 3.x it's possible to combine constructor-arg and property in XML bean definition (check doCreateBean in AbstractAutowireCapableBeanFactory.java, which call createBeanInstance and populateBean next).

另请参见 https://softwareengineering.stackexchange. com/questions/149378/构造器和设置器一起注入弹簧/

这篇关于bean定义中的constructor-arg和property的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆