开发者

Setting values on a child bean

I would like to get a child object in my Spring IoC application context and set a value on it. How can I do this?

Here is the code equivalent:

// The constructor here instantiates the correct child object
MyContainerBean container = new MyContainerBean();
container.getChild().setValue(someValue);
开发者_运维技巧


Do you mean

<bean id="container" class="MyContainerBean">
    <property name="child">
        <bean class="Child">
            <property name="value" value="someValue"/>
        </bean>
    </property>
</bean>

?

Edit: Based on your response, your problem is that you have a violation of Inversion of Control. Objects don't create their own dependencies. They allow them to be injected. The best you can do with XML configuration in this case would probably be to create the container, inject it into some object, and have that object make the changes you need. You could also use Java-based configuration to create and configure the container bean as needed.


If the parent instantiates the child and you can't change that, then inject the value into the parent and have the parent inject it into the child at the appropriate moment. If the value to be injected isn't known at parent creation time then you have to change the design.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜