Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set dynamically a bean reference in Spring?

Tags:

java

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

like image 462
Shashi Avatar asked Feb 03 '12 07:02

Shashi


People also ask

How do you pass parameters dynamically to Spring beans?

String hello(String name) { return "Hello, " + name; } } // and later in your application AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration. class); String helloCat = (String) context. getBean("hello", "Cat"); String helloDog = (String) context.

Who dynamically wires up beans and setting and applies them to your application context?

Instead, when you start up your application, Spring Boot dynamically wires up beans and settings and applies them to your application context. Building applications with Spring Boot is really fast, especially for web applications.


1 Answers

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
like image 190
ndeverge Avatar answered Oct 12 '22 17:10

ndeverge