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

我的未来我决定 提交于 2020-01-05 06:17:23

问题


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


回答1:


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



回答2:


What I want is impossible but requested with https://jira.spring.io/browse/SPR-13348

If you think multiple bean registration is OK please upvote



来源:https://stackoverflow.com/questions/39510702/how-to-register-many-object-as-beans-in-spring-java-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!