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

175
Visualizações
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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

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 :-)

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