如何使用 java spring 在运行时动态更改 bean 的属性? 我有一个 bean mainView,它应该使用“class1”或“class2”作为属性“class”。 该决定应基于属性文件做出,其中属性“withSmartcard”为“Y”或“N”。
应用上下文:
<bean id="mainView"
class="mainView">
<property name="angebotsClient" ref="angebotsClient" />
<property name="class" ref="class1" />
</bean>
<bean id="class1"
class="class1">
<constructor-arg ref="mainView" />
</bean>
<bean id="class2"
class="class2">
<constructor-arg ref="mainView" />
</bean>
属性文件:
withSmartcard=Y
最佳答案
使用 PropertyPlaceHolder 来管理您的属性文件..
<bean id="myPropertyPlaceHolder"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<description>The service properties file</description>
<property name="location" value="classpath:/some.where.MyApp.properties" />
</bean>
并按如下方式更改您的 ref 属性:
<bean id="mainView"
class="mainView">
<property name="angebotsClient" ref="angebotsClient" />
<property name="class" ref="${withSmartCardClassImplementation}" />
</bean>
在您的属性文件 some.where.MyApp.properties 中,添加一个名为 withSmartCardClassImplementation 的键,其值为 class1 或 class2(您选择)。
withSmartCardClassImplementation=class1
关于java - 动态改变 spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/797894/