Spring IDREF用法

时间:2013-01-30 15:07:35

标签: spring

我有一个spring.xml定义如下:

<?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.tutorial.spring.Triangle">
    <property name="pointA">
        <idref bean="pointA"/>
    </property>
    <property name="pointB" ref="pointB"/>
    <property name="pointC" ref="pointC"/>
</bean>
<bean id="pointA" class="org.tutorial.spring.Point">
    <property name="x" value="0"/>
    <property name="y" value="0"/>
</bean>
<bean id="pointB" class="org.tutorial.spring.Point">
    <property name="x" value="100"/>
    <property name="y" value="200"/>
</bean>
<bean id="pointC" class="org.tutorial.spring.Point">
    <property name="x" value="-100"/>
    <property name="y" value="-200"/>
</bean>
</beans>

Point类基本上是一个有2个私有int成员的类。我的问题是我在IDREF上收到如下错误:

Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'org.tutorial.spring.Point' for property 'pointA'; 
nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.tutorial.spring.Point] for property 'pointA': no matching editors or conversion strategy found

据我了解,bean {3}的IDREF(在上述情况下)的目的是存在(错误检查)bean三角形。所以我确实在IDREF元素中提供了bean PointA(string)的名称。为什么我会收到上述错误?

当我认为只是通过提供一个bean(PointA)来检查bean的存在时,它为什么要尝试将字符串转换为Point?

我真的很困惑。请帮忙。感谢。

5 个答案:

答案 0 :(得分:13)

idref元素只是一种防错方法,可以将容器中另一个bean的id(字符串值 - 而不是引用)传递给或者元素。

简单地说,idref元素用于传递字符串值,并且使用idref标记允许容器在部署时验证引用的命名bean实际存在。

考虑以下示例

class FirstBean

class SecondBean

Bean definition in the application context

the calling code for instantiating the beans

output in the console

当我们调用secondBean.getSecondMessage()时,请注意控制台中的输出,该值是使用idref属性设置的firstBean。

请注意:      元素带来价值的常见位置是ProxyFactoryBean bean定义中AOP拦截器的配置。在指定拦截器名称时使用元素可以防止拼写错误的拦截器ID。

答案 1 :(得分:11)

idref用于传递bean的名称(标识符)(即String)。

<idref bean="pointA">与字符串值pointA完全相同,只是如果没有定义这样的bean,Spring会抱怨。

有关详细信息,请参阅the Spring documentation

要传递实际的bean,只需使用ref,就像对pointBpointC一样。

答案 2 :(得分:1)

通过使用'idref'标记,您可以在部署时验证引用的命名bean实际上是否存在。

例如,                                              

<bean id="paulo" class="com.sample.pojo.Author">
    <property name="firstName" value="Paulo" />
    <property name="lastName" value="Coelho" />
    <property name="dateOfBirth" value="24 August 1947" />
    <property name="country" value="India" />
</bean>

如果您定义如下所示的验证器bean,Spring会在部署时使用ids osho和Paulo验证bean。如果在配置文件中找不到任何bean,则spring抛出BeanDefinitionStoreException。

<bean id="validatorBean" class="com.sample.test.BeansValidator">
    <property name="author1">
        <idref bean="osho" />
    </property>

    <property name="author2">
        <idref bean="paulo" />
    </property>
</bean>

以下是完整的工作申请。

package com.sample.pojo;

public class Author {
    private String firstName;
    private String lastName;
    private String dateOfBirth;
    private String country;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(String dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Author [firstName=").append(firstName).append(", lastName=").append(lastName)
                .append(", dateOfBirth=").append(dateOfBirth).append(", country=").append(country).append("]");
        return builder.toString();
    }

}

BeansValidator.java

package com.sample.test;

    public class BeansValidator {
        private String author1;
        private String author2;

        public String getAuthor1() {
            return author1;
        }

        public void setAuthor1(String author1) {
            this.author1 = author1;
        }

        public String getAuthor2() {
            return author2;
        }

        public void setAuthor2(String author2) {
            this.author2 = author2;
        }

    }

<强> myConfiguration.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="osho" class="com.sample.pojo.Author">
        <property name="firstName" value="Osho" />
        <property name="lastName" value="Jain" />
        <property name="dateOfBirth" value="11 December 1931" />
        <property name="country" value="India" />
    </bean>

    <bean id="paulo" class="com.sample.pojo.Author">
        <property name="firstName" value="Paulo" />
        <property name="lastName" value="Coelho" />
        <property name="dateOfBirth" value="24 August 1947" />
        <property name="country" value="India" />
    </bean>

    <bean id="validatorBean" class="com.sample.test.BeansValidator">
        <property name="author1">
            <idref bean="osho" />
        </property>

        <property name="author2">
            <idref bean="paulo" />
        </property>
    </bean>

</beans>

运行HelloWorld.java,不会有任何例外。

package com.sample.test;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    public class HelloWorld {
        public static void main(String args[]) {
            ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

            ((ClassPathXmlApplicationContext) context).close();
        }
    }

现在更新myConfiguration.xml,如下所示。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="osho" class="com.sample.pojo.Author">
        <property name="firstName" value="Osho" />
        <property name="lastName" value="Jain" />
        <property name="dateOfBirth" value="11 December 1931" />
        <property name="country" value="India" />
    </bean>

    <bean id="paulo" class="com.sample.pojo.Author">
        <property name="firstName" value="Paulo" />
        <property name="lastName" value="Coelho" />
        <property name="dateOfBirth" value="24 August 1947" />
        <property name="country" value="India" />
    </bean>

    <bean id="validatorBean" class="com.sample.test.BeansValidator">
        <property name="author1">
            <idref bean="Krishna" />
        </property>

        <property name="author2">
            <idref bean="paulo" />
        </property>
    </bean>

</beans>

在您看到配置文件时,validatorBean会检查ID为'Krishna'的bean。

<bean id="validatorBean" class="com.sample.test.BeansValidator">
        <property name="author1">
            <idref bean="Krishna" />
        </property>

        <property name="author2">
            <idref bean="paulo" />
        </property>
    </bean>

由于id为'Krishna'的bean不存在,最终会出现以下错误。

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'validatorBean' defined in class path resource [myConfiguration.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean name 'Krishna' in bean reference for bean property 'author1'
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
    at com.sample.test.HelloWorld.main(HelloWorld.java:8)

答案 3 :(得分:0)

我必须说,我有点困惑。在您提供praveen的示例中,它将起作用,因为类中的属性是String类型,但在yapkm01的示例中,attribut的类型为Point,您将获得提到的异常。为了能够使用idref,他似乎必须引入另一个String类型的属性,这里是“message”,然后代码看起来像这样:

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

<property name="pointA" ref="zeroPoint"/>

答案 4 :(得分:-1)

你没有做错任何事。您应该在代码中使用<ref>而不是<idref><idref>标记用于创建String类型的值,该值等于引用bean的ID,用于验证目的。