我将代码编辑成此配置:
@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类,并在第二个Java类中扩展以访问RabbitTemplate。 如何在 Java 类中使用 RabbitTemplate?可能已经实施了春季设计的设施?
您可以添加另一个从连接工厂开始创建模板的 bean:
@Bean
public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
return rabbitTemplate;
}
您可以在容器托管类中自动连线它:
@Autowired private RabbitTemplate rabbitTemplate;
您可以将 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;