简体   繁体   中英

How to create and use beans from Command Line Argument in SpringbootApplication and use them?

I am trying to create a batch job using ApplicationRunner in my sprinbootApplication and I want to use the command line arguments as variables in my code. So i want to extract the command line arguments, make beans from them and use them in my code. How to achieve it?

@SpringBootApplication
public class MySbApp implements ApplicationRunner {
  public static void main(String[] args) {
    SpringApplication.run(Myclass.class, args);
  }

  @Autowired
  private Myclass myclass;

  @Override
  public void run(ApplicationArguments args) throws Exception {
    String[] arguments = args.getSourceArgs();
    for (String arg : arguments) {
      System.out.println("HEYYYYYY" + arg);
    }
    Myclass.someMethod();
  }
}

How do I create beans here?

Assume:

// class ...main implements ApplicationRunner { ...

// GenericApplicationContext !!! (but plenty alternatives for/much tuning on this available):
@Autowired
private GenericApplicationContext context;

@Override
public void run(ApplicationArguments args) throws Exception {
  String[] arguments = args.getSourceArgs();
  for (String arg : arguments) {
    System.out.println("HEYYYYYY" + arg);
    // simple sample: register for each arg a `Object` bean, with `arg` as "bean id":
    // ..registerBean(name, class, supplier)
    context.registerBean(arg, Object.class, () -> new Object()); 
  }
}
// ...

Then we can test, like:

package com.example.demo; // i.e. package of main class

import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;

// fake args:
@SpringBootTest(args = {"foo", "bar"})
public class SomeTest {

  // the "testee" ((from) spring context/environment)
  @Autowired
  ApplicationContext ctxt;

  @Test
  public void somke() throws Exception {
    // should contain/know the beans identified by:
    Object foo = ctxt.getBean("foo");
    assertNotNull(foo);
    Object bar = ctxt.getBean("bar");
    assertNotNull(bar);
  }
}

or just like:

  @Autowired
  @Qualifier("foo")
  Object fooBean;

  @Autowired
  @Qualifier("bar")
  Object barBean;

  @Test
  public void somke2() throws Exception {
    assertNotNull(fooBean);
    assertNotNull(barBean);
  }

Refs:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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