質問

コマンドライン引数を解析する Spring コマンドライン アプリケーションを作成している場合、それらを Spring に渡すにはどうすればよいですか?最初にコマンドライン引数を解析してから Spring を初期化するように main() を構造化したいでしょうか?そうであっても、解析された引数を保持するオブジェクトを Spring に渡すにはどうすればよいでしょうか?

役に立ちましたか?

解決

私が考えられる可能性は 2 つあります。

1) 静的リファレンスを設定します。(静的変数は通常は嫌われますが、この場合はコマンド ライン呼び出しが 1 つしかないため問題ありません)。

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

その後、次のように Spring でコマンド ライン引数を参照できます。

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

あるいは (静的変数に完全に反対している場合)、次のこともできます。

2) プログラムで引数をアプリケーション コンテキストに追加します。

 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"
   };

 }

コマンドライン引数の解析は、読者の演習として残しておきます。

他のヒント

私の Spring-CLI ライブラリを見てください - http://github.com/sazzer/spring-cli - これを行うための 1 つの方法として。これにより、Spring コンテキストを自動的にロードするメイン クラスが提供され、Commons-CLI を使用してコマンド ライン引数を自動的に解析して Bean に注入する機能が提供されます。

オブジェクト配列を 2 番目のパラメータとして渡すこともできます。 getBean これはコンストラクターまたはファクトリーへの引数として使用されます。

public static void main(String[] args) {
   Mybean m = (Mybean)context.getBean("mybean", new Object[] {args});
}

Spring 3.1 以降、他の回答で提案されているカスタムコードは必要ありません。チェック コマンドラインプロパティソース, を使用すると、コンテキストに CL 引数を挿入する自然な方法が提供されます。

そして、あなたが幸運な Spring Boot 開発者であれば、次の事実を利用してコードを一歩前進して簡素化できるでしょう。 SpringApplication 以下を与えます:

デフォルトでは、クラスは次の手順を実行してアプリケーションをブートストラップします。

...

commandlinePropertySourceを登録して、コマンドライン引数をスプリングプロパティとして公開する

Spring Boot プロパティの解決順序に興味がある場合は、ご相談ください。 このページ.

次のクラスについて考えてみましょう。

public class ExternalBeanReferneceFactoryBean 
    extends AbstractFactoryBean
    implements BeanNameAware {

    private static Map<String, Object> instances = new HashMap<String, Object>();
    private String beanName;

    /**
     * @param instance the instance to set
     */
    public static void setInstance(String beanName, Object instance) {
        instances.put(beanName, instance);
    }

    @Override
    protected Object createInstance() 
        throws Exception {
        return instances.get(beanName);
    }

    @Override
    public Class<?> getObjectType() {
        return instances.get(beanName).getClass();
    }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }

}

とともに:

/**
 * Starts the job server.
 * @param args command line arguments
 */
public static void main(String[] args) {

    // parse the command line
    CommandLineParser parser = new GnuParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = parser.parse(OPTIONS, args);
    } catch(ParseException pe) {
        System.err.println("Error parsing command line: "+pe.getMessage());
        new HelpFormatter().printHelp("command", OPTIONS);
        return;
    }

    // create root beanFactory
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

    // register bean definition for the command line
    ExternalBeanReferneceFactoryBean.setInstance("commandLine", cmdLine);
    beanFactory.registerBeanDefinition("commandLine", BeanDefinitionBuilder
        .rootBeanDefinition(ExternalBeanReferneceFactoryBean.class)
        .getBeanDefinition());

    // create application context
    GenericApplicationContext rootAppContext = new GenericApplicationContext(beanFactory);
    rootAppContext.refresh();

    // create the application context
    ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] { 
        "/commandlineapp/applicationContext.xml"
    }, rootAppContext);

    System.out.println(appContext.getBean("commandLine"));

}

Main メソッドのストラップ スプリングをブートする例を次に示します。渡されたパラメータを通常どおり取得し、Bean で呼び出す関数 (deployer.execute() の場合) にそれらを文字列として、または適切と思われる任意の形式で取得させます。 。

public static void main(String[] args) throws IOException, ConfigurationException {
    Deployer deployer = bootstrapSpring();

    deployer.execute();
}

private static Deployer bootstrapSpring()
{
    FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext("spring/deployerContext.xml");

    Deployer deployer = (Deployer)appContext.getBean("deployer");
    return deployer;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top