0

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 ?

Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42
userdr725
  • 25
  • 1
  • 6
  • Could you please describe the problem you're trying to solve? Why would you need to create beans at runtime, based on input arguments? Couldn't those arguments instead be parameters to a call on a preexisting bean? – crizzis Nov 30 '22 at 13:59
  • `Myclass` is a class! ... `myclass` is an instance ;) – xerx593 Dec 07 '22 at 00:01

1 Answers1

0

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:

xerx593
  • 12,237
  • 5
  • 33
  • 64