Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Access bean property from another bean

Tags:

java

spring

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!

like image 710
carlspring Avatar asked Oct 05 '13 01:10

carlspring


People also ask

How do you copy properties of beans?

Use PropertyUtils. copyProperties() to copy the properties from one bean to another. The first parameter is the destination bean, and the second parameter is the bean to copy properties from: import org.

What attribute is used to inherit other beans?

By using the parent attribute of bean, we can specify the inheritance relation between the beans. In such case, parent bean values will be inherited to the current bean.


2 Answers

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.

like image 80
Sotirios Delimanolis Avatar answered Sep 22 '22 06:09

Sotirios Delimanolis


try this

<bean id="dataCenter" class="com.foo.DataCenter">
    <property name="configuration" value="#{configurationManager.configuration}"/>
</bean>
like image 41
Evgeniy Dorofeev Avatar answered Sep 19 '22 06:09

Evgeniy Dorofeev