Change spring bean alias with System property

半城伤御伤魂 提交于 2019-12-08 00:21:27

问题


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?


回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/12315589/change-spring-bean-alias-with-system-property

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