我将我的代码编辑到这个配置中:
@SpringBootApplication
public class EndPoint {
String QUEUE_PROCESSING_TRANSACTION = "processing-process-queue";
String QUEUE_DATABASE_TRANSACTION = "database-transa-queue";
......
@Bean
public Queue queueProcessingTransaction() {
return new Queue(QUEUE_PROCESSING_TRANSACTION, true);
}
@Bean
public Queue queueDatabaseEventLogs() {
return new Queue(QUEUE_DATABASE_EVENT_LOGS, true);
}
@Bean
public Binding bindingQueueProcessingTransaction() {
return BindingBuilder.bind(new Queu........
}
@Bean
public CachingConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(HOST);
return connectionFactory;
}
@Bean
public AmqpAdmin amqpAdmin(CachingConnectionFactory connectionFactory) {
RabbitAdmin admin = new RabbitAdmin(connectionFactory);
.........
admin.declareQueue(new Queue(QUEUE_PROCESSING_TRANSACTION, true));
return admin;
}
@Bean
public RabbitTemplate processingTemplate(CachingConnectionFactory connectionFactory) {
RabbitTemplate processingTemplate = new RabbitTemplate(connectionFactory);
processingTemplate.setExchange(EXCHANGE_PROCESSING);
.......
return processingTemplate;
}
之前,我将这个配置用到了Java class中,为了访问RabbitTemplate,我在第二个Java类中进行了扩展。如何在Java类中使用RabbitTemplate?可能已经有用Spring设计的实现工具了吧?
发布于 2018-06-30 04:58:37
您只需添加另一个从连接工厂开始创建模板的bean:
@Bean
public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
return rabbitTemplate;
}
您可以在容器托管类中自动部署它:
@Autowired private RabbitTemplate rabbitTemplate;
发布于 2018-06-30 05:02:19
您可以将RabbitTemplate bean注入到另一个Spring Bean中并使用它,例如,您可以创建一个新的Spring Bean (组件),如下所示:
@Component
public class MyComponent {
@Autowired
private RabbitTemplate template;
public void testRabbitTemplate() {
System.out.println(template);
}
}
请记住,只有当您从Spring上下文中检索MyComponent
时,注入才有效(即,您不能使用new
关键字对其进行实例化)。
您还可以在EndPoint
类中注入相同的RabbitTemplate,只需将以下行添加到类主体中:
@Autowired private RabbitTemplate template;
https://stackoverflow.com/questions/51109221
复制相似问题