如何在测试配置中使用相同的bean但具有不同的属性?

时间:2016-01-20 02:32:56

标签: java spring spring-amqp spring-rabbit spring-rabbitmq

我有单独的配置类,每个Spring Profile创建不同的bean。我希望我的测试尽可能地模拟生产代码,所以我想使用在Spring ‘PROD’ Profile下创建的相同的bean ,但添加/更新专门用于测试的不同属性。实现这一目标的最佳方法是什么?

我的意思是:

@Profile(PROD)
public class ProdConfig {
    @Bean
    public SimpleRabbitListenerContainerFactory containerFactory() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMaxConcurrentConsumers(2);
        ...
        return factory;
    }
}

@Profile(TEST)
public class TestConfig {
    @Bean
    public SimpleRabbitListenerContainerFactory containerFactory() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMaxConcurrentConsumers(2);
        ...
        /**
            The advice chain should only set for testing purposes
        **/
        factory.setAdviceChain(interceptor());
        return factory;
    }

    @Bean
    RetryOperationsInterceptor interceptor() {
        ...
    }
}

理想情况下,我不想复制代码以在SimpleRabbitListenerContainerFactory中设置TestConfig的各种属性。我只想加载ProdConfig,但请致电setAdviceChain(interceptor())

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

@Import(ProdConfig.class)
public class TestConfig {

    @Autowired
    private SimpleRabbitListenerContainerFactory containerFactory;

    @Bean
    RetryOperationsInterceptor interceptor() {
        ...

        this.containerFactory.setAdviceChain(interceptor);

        return interceptor;
    }

}