Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

java - How to set dynamically a bean reference in Spring?

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

and the env.properties file contains the following properties :

x=Dev1
y=Dev2
z=Dev3

or

x=Stag1
y=Stag2
z=Stag3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...