我有两个豆子:
ConfigurationManager中:
public class ConfigurationManager
{
private Configuration configuration;
public void init() { ... } // Loads a configuration
// Getters and setters
}
数据中心:
public class DataCenter
{
private Configuration configuration;
...
// Getters and setters
}
我想从我的DataCenter bean中获取ConfigurationManager的configuration
字段,我不太清楚语法是什么。
这是我的上下文文件:
<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>
有人可以告诉我该怎么做吗?提前谢谢!
答案 0 :(得分:15)
您可以使用Spring Expression Language按名称引用其他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>
在您的情况下,您可以使用
<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>
以类似的方式,您可以使用@Value
annotation in @Bean
methods或use it in @Autowired
methods.
答案 1 :(得分:4)
试试这个
<bean id="dataCenter" class="com.foo.DataCenter">
<property name="configuration" value="#{configurationManager.configuration}"/>
</bean>