简体   繁体   中英

Spring: Access bean property from another bean

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.

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!

You can use Spring Expression Language to refer to other bean properties by name. Here's the example given in the docs

<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 methods or use it in @Autowired methods.

try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM