在我的Spring Boot应用程序中,我有一个@Configuration类:
@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为null。我很困惑,这可能是什么原因?
最佳答案
这是我自己解决的,因为除非采取某些措施,否则基本的Quartz作业都会脱离自动装配模式。
基于https://github.com/davidkiss/spring-boot-quartz-demo,我成功地在其定义中添加了带有@autowiring的Job。
关于java - 尽管已有@Bean,但@Autowired RabbitTemplate为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36747207/