开发者

Spring: Get inline bean by name

I would like to get inner bean by it's name. Is it possible with Spring API?

Right now I'm using such Spring 2.5 API

ConfigurableApplicationContext.getBean(String paramString)

Example of XML:

<bean id="parent" parent="t_Parent">
    <property name="items">
        <bean id="child" parent="t_Child">
            <property name="ABC" value="test"/>
        </b开发者_JS百科ean>
    </property>
</bean>

I would like to get inner (t_Child) bean by id "child". E.g. ConfigurableApplicationContext.getBean("child"). Spring can't find such bean (because it's inner). At the same time .getBean("parent") works fine.

Any thoughts?


You can't.

From the docs:

A element inside the or elements is used to define a so-called inner bean. An inner bean definition does not need to have any id or name defined, and it is best not to even specify any id or name value because the id or name value simply will be ignored by the container.

If you need it like that, define it as a regular bean.


You can't, but you can create you inner bean outside (so it's no longer an inner bean...) and then reference it inside the property:

<bean id="child" parent="t_Child">
    <property name="ABC" value="test"/>
</bean>

<bean id="parent" parent="t_Parent">
    <property name="items" ref="child"/>
</bean>


Apart from the other (mostly valid) answers and solutions, I guess the spring way would be to use the BeanWrapper interface:

final BeanWrapper bw =
    new BeanWrapperImpl(applicationContext.getBean("parent"));
Object innerBean = bw.getPropertyValue("child");

But I guess that implies that there must be a getter for the property (not only a setter).

Reference:

  • BeanWrapper (javadoc, 2.5 version)
  • Bean manipulation and the BeanWrapper (reference, 2.5 version)


If you move up to Spring 3.x, you should be able to do this with the Spring Expression Language. There are examples of directly referencing a bean property from another property (like in link text). The code to do this from Java would be somewhat similar, although I can't find an exact example of this scenario.

However, I would say that if you're trying to use "getBean()", you're doing something wrong. You could just as easily use the SpEL in your context to define a bean or a bean property that references that inner bean.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜