Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda