Search code examples
javaspringspring-bootquartz-scheduler

@Autowired RabbitTemplate is null despite existing @Bean for it


In my Spring Boot application, I have such a @Configuration class:

 @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);
 }
}

and I can see in my logs that it runs just fine.

I also have a Quartz job that is configured like

 @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);
 }
} 

and in this code amqpTemplate is null. I am confused, what could be a reason for this behaviour?


Solution

  • This has been solved myself, as basic Quartz job falls out of auto-wiring schema unless some actions are taken.

    Based on https://github.com/davidkiss/spring-boot-quartz-demo, I was successfully able to add a Job with @autowiring inside its definition.