Search code examples
javaspringvariablesjavabeansparam

Spring Context: It's possible to define variables (not properties) in a XML and use it in runtime to obtain specific referenced beans?


I don't have much experience working with Spring Context and I don't know if this is possible...I'm trying to set into a Spring XML file a variable to define a bean reference (not a property).

Now I have a specidific xml:

keyIntegrator-key1.xml

<import resource="classpath:/events/key-events.xml" />

<context:annotation-config />  

<bean id="keyIntegrator" class="com.emulated.KeySimulator" >
    <property name="readList">
        <list>
            <bean class="com.emulated.ListEventGenerator">
                <property name="eventList">
                     <ref bean="key-1-ok"/>
                </property>
            </bean>
        </list>
    </property>
</bean>

All the keys were defined in another xml file (key-events.xml).

I have to load in Java runtime the bean "keyIntegrator" with only one key, that is a input parameter in the Java program (I use the param to decide the xml file to load)

My question is if it's possible to define a variable inside the xml file and get the referenced bean using this variable:

Something like this:

keyIntegrator-generic.xml

<import resource="classpath:/events/key-events.xml" />    

<context:annotation-config />      

<bean id="keyIntegrator" class="com.emulated.KeySimulator" >    
    <property name="readList">    
        <list>    
            <bean class="com.emulated.ListEventGenerator">    
                <property name="eventList">
                     <ref bean="key-{inputKeyParam}-ok"/>    
                </property>
            </bean>
        </list>
    </property>
</bean>

In the Java program I will need to pass the param to get the bean, something like this:

keySimulatorBean = (KeySimulator) context.getBean("keyIntegrator", "1");

There any way possible to make this ?

Thank you very much!


Solution

  • It is possible to do using Spring Expression Language.

    For example reference to the bean can be defined using system property

    <ref bean="key-#{systemProperties.inputKeyParam}-ok"/>
    

    It will allow to reference different beans depending on provided VM option value, e.g. -DinputKeyParam=1