spring:通过读取另一个 bean 的属性来设置一个 bean 的属性? [英] spring: set property of one bean by reading the property of another bean?
问题描述
是否可以通过读取另一个 bean 的属性来设置一个 bean 的属性?例如,假设我有:
Is it possible to set the property of one bean by reading the property of another bean? For instance, suppose I had:
class A {
void setList(List list);
}
class B {
List getList();
}
我希望 Spring 实例化两个类,并调用 A 的 setList 方法,传入调用 B 的 getList 方法的结果.Spring 配置可能类似于:
I would like Spring to instantiate both classes, and call A's setList method, passing in the result of calling B's getList method. The Spring configuration might look something like:
<bean id="b" class="B"/>
<bean id"a" class="A">
<property name="list" ref="b" ref-property="list"/>
</bean>
唉,这个编造的 XML 不起作用.
Alas, this made-up XML does not work.
为什么不直接将 B 注入 A?因为我不想引入额外的依赖.A 只是依赖 List,而不是 B 上的.
Why not just inject B into A? Because I do not want to introduce the extra dependency. A is only dependent List, not on B.
推荐答案
除了@Kevin 的回答,如果您使用的是 spring 3.0,还可以使用新的 spring 表达式语言来做到这一点
in addition to @Kevin's answer if you are using spring 3.0 it is possible to do this with the new spring expression language
<bean id="a" class="A">
<property name="list"
value="#{b.list}"/>
</bean>
这篇关于spring:通过读取另一个 bean 的属性来设置一个 bean 的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!