首页 文章

如何在Spring(Boot)应用程序的代码中动态添加bean?

提问于
浏览
1

我有一个使用spring-rabbit的Spring(启动)应用程序,我根据需要创建了绑定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 方法?我想要像"for each name in this list, add these three beans with this connection."这样的东西

1 回答

  • 0

    要以编程方式注册任意数量的bean,您需要下拉到较低级别的API . 您可以在配置类上使用 @Import 来引用 ImportBeanDefinitionRegistrar 实现 . 在注册器的 registerBeanDefinitions 方法中,您将为所有bean注册bean定义 .

    如果您希望能够从外部配置将要注册的bean, ImportBeanDefinitionRegistrar 可以是 EnvironmentAware . 这允许您注入 Environment ,以便您可以使用其属性来自定义注册器将注册的bean .

相关问题