如何在SpringbootApplication中从命令行参数创建和使用bean并使用它们?

67up9zun  于 2022-12-02  发布在  Spring
关注(0)|答案(1)|浏览(136)

我正在尝试在我的sprinbootApplication中使用ApplicationRunner创建一个批处理作业,我想在我的代码中使用命令行参数作为变量。所以我想提取命令行参数,从它们中制作bean并在我的代码中使用它们。如何实现?

@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();
  }
}

如何在此处创建Bean?

g6ll5ycj

g6ll5ycj1#

假设:

// 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()); 
  }
}
// ...

然后我们可以测试,比如:

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

或者就像这样:

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

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

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

参考文献:

相关问题