2016-09-15 34 views
0

我想動態註冊多個對象作爲Spring bean。是可能的,沒有BeanFactoryPostProcessor如何在Spring Java Config中將許多對象註冊爲bean?

@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); 
     } 
    } 
} 

實際輸出僅示出一個豆工作:

X

預期:

X YŽ

春4.3.2.RELEASE

+0

其實你有2種豆......指定'型A'的'single'和一個豆一種豆名爲'型List'的'many' 。你的內部(列表中的)不是bean,也不是由Spring管理的。你想要的東西不能直接使用。 –

+0

@ M.Deinum,謝謝。任何提示如何讓它超越框? – michaldo

+0

它會添加什麼。在示例中,它只會增加複雜性,因爲您現在添加了另一種添加Bean的方式。你仍然需要建造他們。如果要添加bean,可以使用「FactoryBean」或創建自己的BeanFactoryPostProcessor或BeanDefinitionRegistryPostProcessor來添加bean的定義。 –

回答

1

你應該用指定A bean定義一種原型參數

@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範圍允許Spring創建一個新的Atemplate執行並註冊一個實例INT上下文。

main執行的結果是,你希望

Y 
Z 
[email protected] 
[[email protected], [email protected]] 
X 
+0

原型,絕妙的主意!我修改了一下答案,因爲'List'是不必要的。我只想要3個bean,1個聲明爲explicite,2個爲動態聲明 – michaldo

+0

原型並不像我那麼優秀。問題是,當原型被創建時,它不能在其他地方重新注入(換句話說,不能被ApplicationContext.getBeanOfType(A.class)加載) – michaldo

相關問題