Skip to content

Instantly share code, notes, and snippets.

@sinujohn
Created September 4, 2014 06:27
Show Gist options
  • Save sinujohn/ca787f0e6730eb9890d5 to your computer and use it in GitHub Desktop.
Save sinujohn/ca787f0e6730eb9890d5 to your computer and use it in GitHub Desktop.
Creating collection of Spring Beans
@Configuration
public class MyConfiguration implements BeanFactoryPostProcessor {
//--- Usual @Bean functions go here ---
private static String[] params = {"param1", "param2", "param3", "param50"};
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
Arrays.asList(params).forEach(param -> createAndRegister((BeanDefinitionRegistry)beanFactory, param));
}
/*
* The bean definition is created and the bean is registered with the Spring Container
*/
private void createAndRegister(BeanDefinitionRegistry registry, String param) {
registry.registerBeanDefinition(getCustomBeanName(param),
BeanDefinitionBuilder.genericBeanDefinition(MyClass.class).addConstructorArgValue(param).getBeanDefinition());
}
/*
* This gives the name of the bean corresponding to a param. The bean gets registered in the Spring container with this name
*/
private String getCustomBeanNameString param) {
return param + "Bean";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment