Spring idref没有像我想的那样工作

时间:2016-03-14 07:53:09

标签: java xml spring

鉴于spring.xml的以下代码,它认为idref有问题...请解释一下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
    <bean id="triangle" class="org.koushik.javabrains.Triangle">

        <property name="pointA">
            <idref bean="zeroPoint"/>
        </property>

        <property name="pointB">
            <bean class="org.koushik.javabrains.Point">
                <property name="x" value="-20" />
                <property name="y" value="0" />
            </bean>
        </property>

        <property name="pointC">
            <bean class="org.koushik.javabrains.Point">
                <property name="x" value="20" />
                <property name="y" value="0" />
            </bean>
        </property>

    </bean>

    <bean id="zeroPoint" class="org.koushik.javabrains.Point">
        <property name="x" value="0" />
        <property name="y" value="0" />
    </bean>
    <alias name="triangle" alias="triangle-alias" />
    <alias name="triangle" alias="triunghi" />
</beans>

从某些来源我发现:

<property name="pointD">
<idref bean="squarePointD"/>
</property>

等于以下

<property name="pointD">
<value>squarePointD</value>
</property>

1 个答案:

答案 0 :(得分:1)

idrefs可以被视为字符串。 idref用于传递bean引用的bean的名称(作为String)。你班上有PointA, pointD,等字符串吗?

由于您似乎指的是自定义类org.koushik.javabrains.Point,因此可能无效。当你想使用idref时,你设置/注入的setter或构造函数参数应该是字符串。容器将验证在部署时实际存在通过idref引用的bean。否则会引发错误。

您可以查看https://stackoverflow.com/a/18539137/668951ref vs idref attributes in spring bean declaration了解详情。