问题
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