Coding Ninja
Coding Ninja

Reputation: 385

Injecting values into spring using command line arguments

I have an application which needs to run twice with different port numbers, is there a way that I can pass the port number as command line arguments and retrieve them in the spring context file.

 <bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
    <property name="brokerURL">
       <value>vm://localhost:${<i>port number goes here</i>}</value>
    </property>
</bean>

Upvotes: 9

Views: 10638

Answers (2)

Jagadeesh Venkata
Jagadeesh Venkata

Reputation: 270

if you dont have any problem with using Static variables this is what you can use..

 public class MyClass{
  public static String[] ARGS;
  public static void main(String[] args) {
        ARGS = args;
   }
}


<bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>#{'vm://localhost:'+argsportnumber}</value>
</property>
</bean>

Upvotes: 1

Mike Pone
Mike Pone

Reputation: 19330

If it is a passed is as a system property, you can do that. Add a -Dport.number=8080 (or whatever port you want) to the JVM command and then change the property value to this :

 <bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL">
           <value>vm://localhost:${port.number}/value>
        </property>
 </bean>

ie.

java -Dport.number=8080 com.package.MyMain

Upvotes: 19

Related Questions