动态改变春豆

dde*_*mek 6 java spring javabeans

如何使用java spring在运行时动态更改bean的属性?我有一个bean mainView,它应该用作属性"class""class1"或"class2".此决定应基于属性文件进行,其中属性"withSmartcard"为"Y"或"N".

ApplicationContext的:

<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>
Run Code Online (Sandbox Code Playgroud)

PropertyFile:

withSmartcard = Y

Oli*_*ier 10

使用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>
Run Code Online (Sandbox Code Playgroud)

并更改您的ref属性如下:

<bean id="mainView"
    class="mainView">
    <property name="angebotsClient" ref="angebotsClient" />
    <property name="class" ref="${withSmartCardClassImplementation}" />
</bean>
Run Code Online (Sandbox Code Playgroud)

在属性文件some.where.MyApp.properties中,添加一个名为withSmartCardClassImplementation的键,它将具有class1或class2(您选择)作为值.

withSmartCardClassImplementation=class1
Run Code Online (Sandbox Code Playgroud)


小智 1

使用类工厂。它可以根据您的财产返回实例。