简体   繁体   English

如何将Spring bean ID注入另一个Spring Configured Bean?

[英]How to inject a Spring bean id into another Spring Configured Bean?

I want to be able to pass a bean ID into another bean by reference. 我希望能够通过引用将一个bean ID传递给另一个bean。 So if I have this: 所以,如果我有这个:

<bean id="specialName" class="my.SpecialBean"/>
<bean id="referenceBean" class="my.ReferenceBean">
    <property name="refId" value="<specialName.name>"/>
</bean>

public class ReferenceBean {

    // The spring injected value of this should be 'specialName'        
    public String refId;

    // getter & setter for refId
}

The reason I need this, it that ReferenceBean is actually a route builder in Camel and it directs messages to SpecialBean through the Spring Registry. 我之所以需要它,是因为ReferenceBean实际上是Camel中的路由构建器,它通过Spring Registry将消息定向到SpecialBean。 I'm new to Spring and Camel, so if this is an ill conceived questions, my apologies. 我是Spring和Camel的新手,所以如果这是一个构思错误的问题,我深表歉意。

You can use Spring-EL - 您可以使用Spring-EL-

<bean id="specialName" class="my.SpecialBean"/>
<bean id="referenceBean" class="my.ReferenceBean">
    <property name="refId" value="#{specialName.name}"/>
</bean>

Why not just put the id statically into refId there? 为什么不将id静态地放入refId中呢? It will not change later so why should you do something complicated here? 以后不会更改,那么为什么要在这里做一些复杂的事情?

<bean id="specialName" class="my.SpecialBean"/>
<bean id="referenceBean" class="my.ReferenceBean">
    <property name="refId" value="specialName"/>
</bean>

What about: 关于什么:

<bean id="specialName" class="my.SpecialBean" />
<bean id="referenceBean" class="my.ReferenceBean">
    <property name="refId" ref="specialName" />
</bean>

This way your bean should be injected (provided you change the String attribute in my.SpecialBean. 这样,您的bean应该被注入(只要您更改my.SpecialBean中的String属性。

Then you can get any attribute you want. 然后,您可以获得所需的任何属性。

You could use the idref element (see Spring XML Beans Schema ): 您可以使用idref元素(请参阅Spring XML Beans Schema ):

<bean id="specialName" class="my.SpecialBean"/>
<bean id="referenceBean" class="my.ReferenceBean">
    <property name="refId">
        <idref bean="specialName"/>
    </property>
</bean>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM