How to register many object as beans in Spring Jav

2019-09-09 10:07发布

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

2条回答
Ridiculous、
2楼-- · 2019-09-09 10:25

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

查看更多
叛逆
3楼-- · 2019-09-09 10:33

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
查看更多
登录 后发表回答