java - 动态改变 spring bean

标签 java spring javabeans

如何使用 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/

相关文章:

java - 使用 DbUtils BeanListHandler 在可重用 JavaFX 数据检索服务上摸索通用类型

java - 集合中 Scala.Long 和 Java.lang.Long 之间的隐式转换

java - 线程中的通知

java - 将属性文件构建到 WAR 文件的顶层,Spring-MVC/Maven

java - Spring post 重定向到 access-denied while get 工作

没有 xml bean 定义的 Spring 组件检测

java - 失败.org.hibernate.HibernateException

java - 如何从 Axis Web 服务返回复杂对象

spring - @Autowired 不应该在没有 @RunWith(SpringRunner.class) 的情况下工作,但可以

Java MYSQL 带复选框选择