Java Spring:从另一个 bean 访问 bean 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19193166/
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: Access bean property from another bean
提问by carlspring
I have two beans:
我有两个豆子:
ConfigurationManager:
配置管理器:
public class ConfigurationManager
{
private Configuration configuration;
public void init() { ... } // Loads a configuration
// Getters and setters
}
DataCenter:
数据中心:
public class DataCenter
{
private Configuration configuration;
...
// Getters and setters
}
I would like to get the configuration
field of the ConfigurationManager from within my DataCenter bean and I'm not quite sure what the syntax is.
我想configuration
从我的数据中心 bean 中获取ConfigurationManager的字段,但我不太确定语法是什么。
Here's my context file:
这是我的上下文文件:
<bean id="configurationManager"
class="com.foo.ConfigurationManager"
init-method="init">
<property name="configurationFile" value="etc/configuration.xml"/>
</bean>
<bean id="dataCenter"
class="com.foo.DataCenter">
<!-- <property name="storages" ref="configurationManager."/> -->
</bean>
Could somebody please show me how to do this? Thanks in advance!
有人可以告诉我如何做到这一点吗?提前致谢!
采纳答案by Sotirios Delimanolis
You can use Spring Expression Languageto refer to other bean properties by name. Here's the example given in the docs
您可以使用Spring 表达式语言按名称引用其他 bean 属性。这是文档中给出的示例
<bean id="numberGuess" class="org.spring.samples.NumberGuess">
<property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/>
<!-- other properties -->
</bean>
<bean id="shapeGuess" class="org.spring.samples.ShapeGuess">
<property name="initialShapeSeed" value="#{ numberGuess.randomNumber }"/>
<!-- other properties -->
</bean>
In your case, you could use
在你的情况下,你可以使用
<bean id="configurationManager"
class="com.foo.ConfigurationManager"
init-method="init">
<property name="configurationFile" value="etc/configuration.xml"/>
</bean>
<bean id="dataCenter"
class="com.foo.DataCenter">
<property name="storages" value="#{configurationManager.configuration}"/>
</bean>
In similar fashion, you can use @Value
annotation in @Bean
methodsor use it in @Autowired
methods.
以类似的方式,您可以@Value
在@Bean
方法中使用注解或在方法中使用它@Autowired
。
回答by Evgeniy Dorofeev
try this
尝试这个
<bean id="dataCenter" class="com.foo.DataCenter">
<property name="configuration" value="#{configurationManager.configuration}"/>
</bean>