2

I try to figure out whether it's possible to change a spring alias configuration through a system property.

That's the configuration:

<beans>
    <bean id="beanOne" ... />
    <bean id="beanTwo" ... />
    <bean id="beanThree" ... />
    <alias name="beanOne" alias="beanToUse" />

    <bean id="consumer" ...>
        <constructor-arg ref="beanToUse" />
    </bean>
</beans>

I'd like to be able to use a JVM property e.g. with -Duse=beanThree to select another bean for the alias.

Unfortunately using the straight forward solution <alias name="#{systemProperties.use}" alias="beanToUse" /> throws a NoSuchBeanDefinitionException exception :(

Any suggestions?

pagid
  • 13,559
  • 11
  • 78
  • 104
  • Did you check this thread? http://stackoverflow.com/questions/317687/inject-property-value-into-spring-bean – Chris Sep 07 '12 at 09:47
  • Yes I did but using properties to retrieve arguments themselves is not the problem here ... of course using that technic would enable to introduce a proxy which is then used instead of the alias - but as I said, that wasn't the question. – pagid Sep 07 '12 at 10:01

2 Answers2

2

Did you try to use spring 3.1 profiles?

<beans>
    <bean id="beanOne" ... />
    <bean id="beanTwo" ... />
    <bean id="beanThree" ... />
    <beans profile="A">
      <alias name="beanOne" alias="beanToUse" />
    </beans>

    <beans profile="B">
      <alias name="beanTwo" alias="beanToUse" />
    </beans>

    <bean id="consumer" ...>
        <constructor-arg ref="beanToUse" />
    </bean>
</beans>

and choose through system property -Dspring.profiles.active=A. I haven't tried aliases in profiles but you could just have alternative beanToUse definitions in each profile:

<beans>
    <beans profile="A">
      <bean id="beanToUse" ... defined as beanOne ... />
    </beans>

    <beans profile="B">
      <bean id="beanToUse" ... defined as beanTwo .../>
    </beans>

    <bean id="consumer" ...>
        <constructor-arg ref="beanToUse" />
    </bean>
</beans>
mrembisz
  • 12,722
  • 7
  • 36
  • 32
  • Btw. nice that in addition: ` ... ` works as expected and finally leads to the behavior I intended. Thanks a lot :) – pagid Sep 08 '12 at 11:28
1

Here's another way to do this using SpEL. I have two implementations of DataStrategy type with bean ids testDataStrategy and realDataStrategy

I can choose between the beans by setting the property 'data.strategy' in the Property file in my Java project.

<bean id="myBeanId" class="com.some.path.MyBeanClass" >
    <property name="dataStrategy" value="#   {'${data.strategy}'.equalsIgnoreCase('TEST_DATA') ? testDataStrategy : realDataStrategy}" />
</bean>