@Bean注解参数(引用类型)加载的方式
如果参数类型所对应的实例在spring容器中只有一个,则默认选择这个实例。如果有多个,则需要根据参数名称来选择(参数名称就相当于是spring的配置文件中的bean的id)
如:
@Bean
public ConnectionFactory connectionFactory1() {
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
cachingConnectionFactory.setHost("xxxx");
cachingConnectionFactory.setUsername("xxxx");
cachingConnectionFactory.setPassword("xxxx");
cachingConnectionFactory.setPort(111);
return cachingConnectionFactory;
}
@Bean
public ConnectionFactory connectionFactory2() {
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
cachingConnectionFactory.setHost("ttt");
cachingConnectionFactory.setUsername("ttt");
cachingConnectionFactory.setPassword("ttt");
cachingConnectionFactory.setPort(111);
return cachingConnectionFactory;
}
@Bean
public SimpleRabbitListenerContainerFactory bookingContainerFactory(SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory1) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setPrefetchCount(5);
factory.setConcurrentConsumers(5);
configurer.configure(factory, connectionFactory1);
return factory;
}
如上:定义2个connection,在SimpleRabbitListenerContainerFactory的最后一个参数里面,ConnectionFactory connectionFactory1 。
先按照类型ConnectionFactory查找,发现有2个相同类型的ConnectionFactory., connectionFactory1 和connectionFactory2。接着就按照参数名字查找
这里指定的参数名字是connectionFactory1,就使用connectionFactory1这个bean.
若是使用的是:ConnectionFactory connectionFactory2,就使用的connectionFactory2这个bean.
如果参数名字是其他的不存在的bean,此时只能按照之前的类型来找,由于有2个相同类型的实例,所以会报错
————————————————
版权声明:本文为CSDN博主「EmineWang」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/a718515028/article/details/89406589