Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda