@Autowired RabbitTemplate 为 null,尽管它存在 @Bean

@Autowired RabbitTemplate is null despite existing @Bean for it

在我的Spring启动应用程序中,我有这样一个@Configurationclass:

 @Configuration
 public class AmqpConnectionConfig {
    @Bean
    @Primary   // has to be here because of https://github.com/spring-projects/spring-boot/issues/2011
    AmqpTemplate inquiryRabbitTemplate(ConnectionFactory factory) {
    RabbitTemplate rabbitTemplate = new RabbitTemplate(factory);
    return rabbitTemplate;
}


 @Bean
 ConnectionFactory connectionFactory() {
   ConnectionFactory factory = new  ConnectionFactory();
   // Some host/port/password setup skipped...
   return new CachingConnectionFactory(factory);
 }
}

我可以在我的日志中看到它运行得很好。

我也有一个 Quartz 作业,配置如下

 @Service
 public class QuartzMockingJob implements Job {

 @Autowired
 AmqpTemplate amqpTemplate;

 public QuartzMockingJob() {
    // Instances of Job must have a public no-argument constructor.
}

public void execute(JobExecutionContext context) throws JobExecutionException {
    // here I create object called "mock"
    if (amqpTemplate!=null) {
        amqpTemplate.convertAndSend("amq.fanout", "my.routing.key", mock);
 }
} 

在此代码中,amqpTemplate 为空。我很困惑,这种行为的原因可能是什么?

我自己已经解决了这个问题,因为除非采取一些措施,否则基本的 Quartz 作业会脱离自动装配模式。

基于https://github.com/davidkiss/spring-boot-quartz-demo,我成功地添加了一个在其定义中带有@autowiring 的作业。