Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
How to create beans dynamically using a DI framework

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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);
     // ...
   }
 }
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!