Change spring bean alias with System property

梦想的初衷 提交于 2019-12-06 04:58:12

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>

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!