2016-10-26 26 views
1

我有一個使用彈簧兔彈簧(引導)應用程序,我創建綁定豆需要像這樣:如何在Spring(Boot)應用程序的代碼中動態添加Bean?

 
import org.springframework.amqp.core.*; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 

@Configuration 
public class QueueBindings { 

    // first binding 

    @Bean 
    public Queue firstQueue(@Value("${rabbitmq.first.queue}") String queueName) { 
     return new Queue(queueName); 
    } 

    @Bean 
    public FanoutExchange firstExchange(@Value("${rabbitmq.first.exchange}") String exchangeName) { 
     return new FanoutExchange(exchangeName); 
    } 

    @Bean 
    public Binding firstBinding(Queue firstQueue, FanoutExchange firstExchange) { 
     return BindingBuilder.bind(firstQueue).to(firstExchange); 
    } 

    // second binding 

    @Bean 
    public Queue secondQueue(@Value("${rabbitmq.second.queue}") String queueName) { 
     return new Queue(queueName); 
    } 

    @Bean 
    public FanoutExchange secondExchange(@Value("${rabbitmq.second.exchange}") String exchangeName) { 
     return new FanoutExchange(exchangeName); 
    } 

    @Bean 
    public Binding secondBinding(Queue secondQueue, FanoutExchange secondExchange) { 
     return BindingBuilder.bind(secondQueue).to(secondExchange); 
    } 

} 

我的問題是,目前只有兩件,每3種豆信息,隊列名稱和交換名稱。

有沒有辦法在上下文中添加任意數量的bean,而不是複製和粘貼一堆@Bean方法?我想要「爲這個列表中的每個名稱,像這樣連接添加這三個bean」。

回答

0

要以編程方式註冊任意數量的bean,您需要下拉到較低級別的API。您可以在配置類上使用@Import來引用ImportBeanDefinitionRegistrar實現。在註冊商的registerBeanDefinitions方法中,您將註冊所有bean的bean定義。

如果您希望能夠在外部配置將要註冊的bean,ImportBeanDefinitionRegistrar可以是EnvironmentAware。這使您可以注入Environment,以便您可以使用其屬性來自定義註冊服務商將註冊的bean。

+0

我終於開始嘗試這種方法。我遇到的問題是'Environment'不允許你處理像地圖這樣的屬性;你可以要求一個已知的財產,但你不能要求「在這個財產下的所有價值將其視爲虛線的路徑」。 Spring Boot能夠映射到地圖,但我不知道如何從註冊服務器中訪問其他bean。 –

相關問題