论坛首页 Java企业应用论坛

idref用法的迷惑?

浏览 6109 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2005-03-25  
我的理解是idref的用法和ref用法应该一样的啊,但事实是却不是。看下面的代码:
<bean id="exampleBean1" class="com.company.wws.test.ExampleBean1">
		<property name="bean2"><idref local="exampleBean2"/></property>
	</bean>
	<bean id="exampleBean2" class="com.company.wws.test.ExampleBean2"/>


上面这段代码由问题,出现异常,但改为ref就可以了。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'exampleBean1' defined in resource loaded through InputStream: Error setting property values; nested exception is org.springframework.beans.PropertyAccessExceptionsException: PropertyAccessExceptionsException (1 errors);; nested propertyAccessExceptions are: [org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.lang.String] to required type [com.company.wws.test.ExampleBean2] for property 'bean2']
PropertyAccessExceptionsException (1 errors);
org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.lang.String] to required type [com.company.wws.test.ExampleBean2] for property 'bean2'
	at org.springframework.beans.BeanWrapperImpl.doTypeConversionIfNecessary(BeanWrapperImpl.java:1016);
   发表时间:2005-03-25  
idref和ref用法不一样的呀。
from spring reference:
An idref element is simply a shorthand and error-proof way to set a property to the String id or name of another bean in the container.

idref只是对另外一个bean的id或者名称的引用(String)。这样的好处是可以让spring检查是不是真的有一个bean叫这样一个名字。否则容易出现拼写错误但是难以发现。
0 请登录后投票
   发表时间:2005-03-25  
idref仅仅是针对String类型的property,只不过利用了xml parser来强制要求该string必须为一个已存在bean的id。
0 请登录后投票
   发表时间:2005-03-25  
你们说得我明白,文档我看过,但如果用ref,那我在bean1里引用bean2的方法,如果是个string类型的属性,
dref仅仅是针对String类型的property,只不过利用了xml parser来强制要求该string必须为一个已存在bean的id。

怎么在bean1里引用bean2?
看下面代码:
bean1 类文件:
public class ExampleBean1
{
    private ExampleBean2 bean2;
    /**
     * @return Returns the bean2.
     */
    public ExampleBean2 getBean2(); {
        return bean2;
    }
    /**
     * @param bean2 The bean2 to set.
     */
    public void setBean2(ExampleBean2 bean2); {
        this.bean2 = bean2;
    }
    public void printMsg();
    {
               bean2.printMsg();;    }
    
}
0 请登录后投票
   发表时间:2005-03-25  
:oops: 偶被你搞糊涂了。上面的例子,只要用ref bean="bean2" 就可以了,这个不是idref适用的地方呀。你的意思能否表述的更清楚一点?
0 请登录后投票
   发表时间:2005-03-25  
de3light 写道
:oops: 偶被你搞糊涂了。上面的例子,只要用ref bean="bean2" 就可以了,这个不是idref适用的地方呀。你的意思能否表述的更清楚一点?

呵呵,是啊,如果用ref的话,我上面贴的代码就已经通过了。我只是今天看文档的时候,看到idref,所以就试试,idref没用过,能说说是怎么用的吗?
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics