Java spring:通过读取另一个 bean 的属性来设置一个 bean 的属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1602640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
spring: set property of one bean by reading the property of another bean?
提问by Landon Kuhn
Is it possible to set the property of one bean by reading the property of another bean? For instance, suppose I had:
是否可以通过读取另一个 bean 的属性来设置一个 bean 的属性?例如,假设我有:
class A {
void setList(List list);
}
class B {
List getList();
}
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:
我希望 Spring 实例化这两个类,并调用 A 的 setList 方法,传入调用 B 的 getList 方法的结果。Spring 配置可能类似于:
<bean id="b" class="B"/>
<bean id"a" class="A">
<property name="list" ref="b" ref-property="list"/>
</bean>
Alas, this made-up XML does not work.
唉,这个编造的 XML 不起作用。
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.
为什么不直接将 B 注入 A?因为我不想引入额外的依赖。A 只是依赖 List,而不是 B。
采纳答案by Gareth Davis
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
除了@Kevin 的回答之外,如果您使用的是 spring 3.0,则可以使用新的 spring 表达式语言来执行此操作
<bean id="a" class="A">
<property name="list"
value="#{b.list}"/>
</bean>
回答by Kevin
There are a couple of ways. Here is one:
有几种方法。这是一个:
<bean id="b" class="B"/>
<bean id="a" class="A">
<property name="list">
<bean class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
<property name="targetObject" ref="b"/>
<property name="propertyPath" value="list"/>
</bean>
</property>
</bean>
Also see the <util:property-path/>
element
回答by Rupesh
If you are trying to do the same for a constructor then do this.
如果您尝试对构造函数执行相同操作,请执行此操作。
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg type="javax.sql.DataSource" value="#{jdbc.dataSource}">
</constructor-arg>
</bean>
Here "jdbc" is as mentioned below that has property "dataSource" with getter and setter and initilized as:
这里的“jdbc”如下所述,它具有带有 getter 和 setter 的属性“dataSource”,并初始化为:
<bean id="jdbc" class="com.la.activator.DataSourceProvider">
<property name="myDataSourcePool" ref="dsPoolService"/>
</bean>