如何在Spring中动态设置bean引用? [英] How to set dynamically a bean reference in Spring?

查看:147
本文介绍了如何在Spring中动态设置bean引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<bean id="Mybean" class="Bean">   
  <property name="config" ref="dev"/>   
</bean>

<bean id="dev" class="Dev">
  <property name="x" ref="Dev1">
  <property name="y" ref="Dev2">
  <property name="z" ref="Dev3">
</bean>

<bean id="stag" class="Dev">
  <property name="x" ref="Stag1">
  <property name="y" ref="Stag2">
  <property name="z" ref="Stag3">
</bean>

在上面的场景中, config 属性在bean MyBean 中从环境更改为环境。在开发时,配置的引用更改为 dev 。在暂存中,引用更改为 stag 。在弹出文件中检查时出现问题。我们必须在每次检查之前分析配置的引用。如果配置了值为 dev 的config,我们可能需要解释很多问题。

In the above scenario, the config property in the bean MyBean change from environment to environment. At the time of dev, reference of config change to dev. And in staging, the reference change to stag. The problem comes at the time of checked in the spring file. We have to analyze everytime the reference of config before checked in. If the reference of config with the value of dev checked in, we might have to explain a lot of questions.

是否有任何解决方案可以让它自动化?

注意:Spring版本是2.0.1

Is there any solution to solve to make it automate?
Note: Spring version is 2.0.1

推荐答案

使用Spring的PropertyPlaceholderConfigurer,删除未使用的bean:

Use the PropertyPlaceholderConfigurer from Spring, and remove an unused bean :

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
         <value>env.properties</value>
     </property>
</bean>

<bean id="Mybean" class="Bean">   
  <property name="config" ref="config"/>   
</bean>

<bean id="config" class="Config">
  <property name="x" ref="${x}">
  <property name="y" ref="${y}">
  <property name="z" ref="${z}">
</bean>

和env.properties文件包含以下属性:

and the env.properties file contains the following properties :

x=Dev1
y=Dev2
z=Dev3

x=Stag1
y=Stag2
z=Stag3

这篇关于如何在Spring中动态设置bean引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆