简体   繁体   English

从xml应用程序上下文中弹簧加载命令行参数

[英]Spring load command line arguments from xml application context

How can I use varargs from Spring application context xml? 如何在Spring应用程序上下文XML中使用varargs?

java -jar my.jar --variable=value

application-context.xml 应用程序的context.xml

<bean id="fooClassInstance" class="my.package.FooClass">
    <property name="myproperty" value="${variable}" />
</bean>

Try to use System properties: 尝试使用系统属性:

java -Dvariable=value -jar my.jar

That either works out of the box or you need to tell the app context to look at system properties when it expands variables. 这要么开箱即用,要么您需要告诉应用程序上下文在扩展变量时查看系统属性。 It's been a while since I tried that. 自从我尝试以来已经有一段时间了。

A good starting point is PropertySourcesPlaceholderConfigurer . 一个很好的起点是PropertySourcesPlaceholderConfigurer

When you do something like this in your Spring XML config 当您在Spring XML配置中执行类似的操作时

<bean id="fooClassInstance" class="my.package.FooClass">
    <property name="myproperty" value="${variable}" />
</bean>

Spring uses PropertyPlaceholderConfigurer to search for those variables in System/enviroment variables and/or list of predefined properties files. Spring使用PropertyPlaceholderConfigurer在系统/环境变量和/或预定义属性文件列表中搜索那些变量。

So the easiest way is to pass that value as a system or environment variable with -Dvariable=value . 因此,最简单的方法是使用-Dvariable=value将该值作为系统或环境变量进行-Dvariable=value

If you want to pass those values as arguments into min you can still do hacks like 如果您想将这些值作为参数传递给min您仍然可以像

public static void main(String[] args) {
    // parse arguments into key, value pairs
    System.setProperty(<key>, <value>);
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(<your XML config file>);
    // use Spring context to get beans
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM