Spring:从另一个bean访问bean属性

17

我有两个豆子:

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>

有人可以演示一下如何做吗?提前谢谢!


1
可能有用:https://dev59.com/XnI-5IYBdhLWcg3w8dUQ?rq=1 - Chris Hayes
@ChrisHayes,确实有效,谢谢!但是我想知道,有没有更简洁的方法来完成这个任务,少些样板配置,或者这是唯一/正确的方法...? - carlspring
2个回答

18
你可以使用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>

在您的情况下,您可以使用
<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>

类似的,您可以在@Bean方法中使用@Value注解,或者@Autowired方法中使用它。


@carlspring 它也可以与自定义类一起使用,假设您拥有适当的访问器。如果您愿意,您还可以使用构造函数参数并指定参数类型。 - Sotirios Delimanolis
@Sotiros,有没有一种方法可以定义一个bean,它实际上是已定义的bean的字段/属性?我的意思是,如果我有beanA并想定义一个新的bean(beanB),它是beanA.foo的引用? - carlspring
@carlspring 那不就是我们上面正在做的吗? - Sotirios Delimanolis
不,以上代码中,我是将beanA的属性f注入到了beanB中。我能否将beanA.f作为一个独立的bean beanC来获取? - carlspring
1
如果我正确理解您提出的建议,那么这将违背IoC和依赖注入的目的。您提出的不是创建beanC并将其注入到beanA.f中,而是创建beanA,然后从f创建一个bean。无论如何,Spring不能做到这一点。 - Sotirios Delimanolis
显示剩余2条评论

5

尝试这个

<bean id="dataCenter" class="com.foo.DataCenter">
    <property name="configuration" value="#{configurationManager.configuration}"/>
</bean>

谢谢!你们两个的答案都是正确的。我选择Sotiros的答案,因为它更详细一些。 - carlspring

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接