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

167
Views
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 answers
Answer question

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 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!