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

240
Vistas
How to create multiple beans of same type according to configuration in Spring?

I'm trying to create a specified number of beans of a same type in Spring.

I've tried:

@Bean(name = "beanList")
public List<MyBean> beanList(
        @Value("${number:1}") int number
        ) {
    List<MyBean> beanList = new ArrayList<>(number);
    for (int i = 0; i < number; i++) {
        beanList.add(new MyBean());
    }
    return beanList;
}

But this is not what expected.

In this way, the bean "beanList" is maintained by spring context, instead of it's elements, so I can't specify a name and init method or destroy method for each element in the list.

Any ideas?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You could have a look at BeanFactoryPostProcessor, I tried with following code and it's working just fine, Beans depends on MyBean could also be autowired:

@Configuration
public class AppConfig implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (int i = 0; i < 3; i++) {
            System.out.println("register my bean: " + i);
            beanFactory.registerSingleton("bean-" + i, new MyBean("MyBean-" + i));
        }
    }
}

Since you have complete control of creation process of MyBean instance, you can simply pass other beans in through constructor if it's necessary. Hope this could be helpful to you :-)

about 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