如何解决Spring无法解析的循环引用,如果配置类移动到依赖
在 Spring-boot-starter-quartz
中,开发人员需要创建一个 SchedulerFactoryBean
类型的 Bean,该 Bean 创建一个 Scheduler
类型的 bean 并将其添加到 spring 上下文中。
这是我用于该实现的配置类
@Configuration
public class MyQuartzConfiguration {
QuartzProperties quartzProperties;
DataSource dataSource;
ApplicationContext applicationContext;
@Autowired
Scheduler scheduler;
public MyQuartzConfiguration (QuartzProperties quartzProperties,DataSource dataSource,ApplicationContext applicationContext) {
this.quartzProperties = quartzProperties;
this.dataSource = dataSource;
this.applicationContext = applicationContext;
}
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
Properties properties = new Properties();
properties.putAll(quartzProperties.getProperties());
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setDataSource(dataSource);
factory.setJobFactory(new MyAutowirableJobFactory(applicationContext));
factory.setQuartzProperties(properties);
return factory;
}
@PostConstruct
public void scheduleJobs() throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob()
.ofType("a.b.mclass")
.withIdentity(JobKey.jobKey("someKey))
.build();
scheduler.scheduleJob(jobDetail,TriggerBuilder.newTrigger()
.forJob(jobDetail)
.withSchedule(CronScheduleBuilder.cronSchedule("myCronExpression"))
.build());
}
我在上下文中有另一个组件,我在其中编织了 Scheduler
以根据用户请求以编程方式触发一些不同作业的一次性运行。
@Component
public class MyService {
private final Scheduler scheduler;
public MyService (Scheduler scheduler) {
this.scheduler = scheduler;
}
......
......
......
}
上面提到的所有这些代码都可以正常工作。
现在为了可重用性,我将 MyQuartzConfiguration
和一些更多与调度相关的通用业务代码提取到自己的 jar 中,并作为 Maven 依赖项添加到不同的服务中。
但是现在当我启动微服务时。我得到以下循环依赖错误。无需更改代码,类仅移动到 jar 中。
Error creating bean with name 'MyQuartzConfiguration'
Unsatisfied dependency expressed through field 'scheduler';
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'schedulerFactoryBean':
Requested bean is currently in creation: Is there an unresolvable circular reference?
我可以通过在 @Lazy
构造函数中将其标记为 MyService
来解决这个问题,并且在启动后服务中需要时间调度程序时,bean 已经被初始化。这样上面的问题就可以解决了
但我的问题是
-
转换为依赖时出现这种行为的原因是什么。
-
除了在服务中将其标记为 Lazy 之外,还有没有更好的方法来处理这个问题?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。