Home > Software engineering >  How to create beans dynamically using a DI framework
How to create beans dynamically using a DI framework

Time:01-24

requirement is like this: user input is single character followed by an array of integers, such as 'A 1 2', 'B 3 4 5', 'C 1', etc. The single character means which class to construct and integers are input parameter to that constructor. Please note different classes might need different number of integers.

Then we need to write a program to parse user input and create objects accordingly.

My approach was to use regular expression for parsing and hard code which class to call.

But another senior developer said a better idea would be using dependency injection to automatically create objects based on user input. He gave another hint to create an interface and use spring framework dependency injection (not spring boot).

I am still confused how to create beans dynamically in this way. Can anybody help please?

CodePudding user response:

You can create a common interface for the classes that can be created, and a Factory bean that transforms the input.

// common interface
interface MyObject {
  void someMethod();
}
class A implements MyObject {
  public A(List<Integer> params) { ... }
}
class B implements MyObject {
  public B(List<Integer> params) { ... }
}

// parsed data
class Input {
 char character;
 List<Integer> ints;
 // getters, setters
}
interface MyObjectFactory {
  public MyObject apply(Input input);
}

@Bean
class MyObjectFactory implements MyObjectFactory {
  public MyObject apply(Input input) {
    // create object from input, eg switch over input.getCharacter()
  };
}
// injected
class MyClientService {
 @Autowired
 MyObjectFactory objectFactory;

 public void doStuff() {
   List<Input> parsedInputs = parse(something);
   for (Input input : parsedInputs) {
     MyObject object = objectFactory.apply(input);
     // ...
   }
 }
}
  •  Tags:  
  • Related