java 使用命令行参数将值注入 spring
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14571342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Injecting values into spring using command line arguments
提问by Coding Ninja
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.
我有一个应用程序需要使用不同的端口号运行两次,有没有办法可以将端口号作为命令行参数传递并在 spring 上下文文件中检索它们。
<bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>vm://localhost:${<i>port number goes here</i>}</value>
</property>
</bean>
采纳答案by Jagadeesh Venkata
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>
回答by Mike Pone
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 :
如果它是作为系统属性传递的,则可以这样做。将 -Dport.number=8080(或您想要的任何端口)添加到 JVM 命令,然后将属性值更改为:
<bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>vm://localhost:${port.number}/value>
</property>
</bean>
ie.
IE。
java -Dport.number=8080 com.package.MyMain