Search code examples
springspring-java-config

How to register many object as beans in Spring Java Config?


I would like dynamically register multiple objects as Spring beans. Is is possible, without BeanFactoryPostProcessor?

@Configuration public class MyConfig {

    @Bean A single() { return new A("X");}

    @Bean List<A> many() { return Arrays.asList(new A("Y"), new A("Z"));}

    private static class A {

        private String name;

        public A(String name) { this.name = name;}

        @PostConstruct public void print() {
            System.err.println(name);
        }
    }
}

Actual output shows only one bean is working:

X

Expected:

X Y Z

Spring 4.3.2.RELEASE


Solution

  • You should specify your A bean definition kind of prototype with a parameter

    @Configuration
    public class MyConfig {
    
        @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
        A template(String seed) {
            return new A(seed);
        }
    
        @Bean
        String singleA() {
            return "X";
        }
    
        @Bean
        List<A> many() {
            return asList(template("Y"), template("Z"));
        }
    
        private static class A {
    
        }
    
        public static void main(String[] args) {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
            A a = (A) context.getBean("template");
            System.out.println(a);
            List<A> l = (List<A>) context.getBean("many");
            System.out.println(l);
        }
    }
    

    prototype scope allows Spring to create a new A with every template execution and register an instance into context.

    The result of main execution is as you expect

    Y
    Z
    MyConfig$A@15bfd87
    [MyConfig$A@543e710e, MyConfig$A@57f23557]
    X