Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating a collection of beans in Spring using @Configuration
    text
    copied!<p>How can I create a collection of beans that will be properly managed by Spring using a class with a @Configuration annotation.</p> <p>I would like to do something like this:</p> <pre><code>@Configuration public Config { @Autowired private SomeConfiguration config; @Bean public List&lt;MyBean&gt; myBeans() { List&lt;MyBean&gt; beans = new ArrayList&lt;MyBean&gt;(); for (Device device : config.getDevices()) { beans.add(new MyBean(device)); } return beans; } } </code></pre> <p>But the MyBean instances aren't post processed. So their @Autowired methods are not called, the beans are not registered as mbeans and etc. The list is however accessible so that I can autowire a List of MyBean objects.</p> <p>I cannot use something like:</p> <pre><code>@Configuration public Config { @Autowired private SomeConfiguration config; @Bean public MyBean myBean1() { ... } @Bean public MyBean myBean2() { ... } } </code></pre> <p>Since the number of MyBean instances are not known before runtime. The reason I want to do this is because we are controlling a physical machine that have a variable amount of components. And I want to have one bean per component.</p> <p>I'm currently achieving our goal by using a BeanFactoryPostProcessor like this:</p> <pre><code>@Component public class MyBeansFactoryPostProcessor implements BeanFactoryPostProcessor { @Autowired private SomeConfiguration config; @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeanException { for (Device device : config.getDevices()) { createAndRegister(BeanDefinitionRegistry) beanFactory, device); } } private void createAndRegister(BeanDefinitionRegistry registry, Device device) { register.registerBeanDefinition("device" + device.getId(), BeanDefinitionBuilder.genericBeanDefinition(MyBean.class).addConstructorArgValue(device).getBeanDefinition()); } } </code></pre> <p>But this just feels like a really ugly hack.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload