处理命令行参数和Spring

处理命令行参数和Spring

本文介绍了处理命令行参数和Spring的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编写一个解析命令行参数的Spring命令行应用程序时,如何将它们传递给Spring?我想要我的main()结构化,以便它首先解析命令行参数,然后在春天?

When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?

推荐答案

我可以想到的两种可能性。

Two possibilities I can think of.

1)设置静态引用。 (静态变量,虽然通常被皱眉,在这种情况下是OK,因为只能有一个命令行调用)。

1) Set a static reference. (A static variable, although typically frowned upon, is OK in this case, because there can only be 1 command line invocation).

    public class MyApp {
      public static String[] ARGS;
        public static void main2(String[] args) {
          ARGS = args;
          // create context
      }
    }

引用Spring中的命令行参数:

You can then reference the command line arguments in Spring via:

<util:constant static-field="MyApp.ARGS"/>

或者(如果你完全反对静态变量),你可以:

Alternatively (if you are completely opposed to static variables), you can:

2)以编程方式将args添加到应用程序上下文:

2) Programmatically add the args to the application context:

public class MyApp2 {
public static void main(String[] args) {
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

     // Define a bean and register it
    BeanDefinition beanDefinition = BeanDefinitionBuilder.
        rootBeanDefinition(Arrays.class, "asList")
        .addConstructorArgValue(args).getBeanDefinition();
    beanFactory.registerBeanDefinition("args", beanDefinition);
    GenericApplicationContext cmdArgCxt = new GenericApplicationContext(beanFactory);
    // Must call refresh to initialize context
    cmdArgCxt.refresh();

    // Create application context, passing command line context as parent
    ApplicationContext mainContext = new ClassPathXmlApplicationContext(CONFIG_LOCATIONS, cmdArgCxt);

    // See if it's in the context
    System.out.println("Args: " + mainContext.getBean("args"));
}

private static String[] CONFIG_LOCATIONS = new String[] {
    "applicationContext.xml"
};

}

解析命令行参数将作为练习留给读者。

Parsing the command line arguments is left as an exercise to the reader.

这篇关于处理命令行参数和Spring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 19:35