对我有用的代码:
数据库配置的一部分如下所示:
@Profile("!dbClean")
@Bean(initMethod = "migrate")
public Flyway flywayNotADestroyer() {
Flyway flyway = new Flyway();
flyway.setDataSource(dataSource());
flyway.setInitOnMigrate(true);
return flyway;
}
@Profile("dbClean")
@Bean(initMethod = "migrate")
public Flyway flywayTheDestroyer() {
Flyway flyway = new Flyway();
flyway.setDataSource(dataSource());
flyway.setInitOnMigrate(true);
flyway.clean();
return flyway;
}
该配置代表两个独占 bean。一个在“dbClean”配置文件存在时创建,另一个在它不存在时创建。忍受我,忘记代码重复。
另一个配置管理 Quartz 配置:
@Autowired
private Flyway flyway;
@Bean
public SchedulerFactoryBean quartzScheduler(Flyway flyway) throws SchedulerException {
SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();
quartzScheduler.setDataSource(dataSource);
quartzScheduler.setTransactionManager(transactionManager);
quartzScheduler.setOverwriteExistingJobs(true);
quartzScheduler.setSchedulerName("mysuperduperthegratest-quartz-scheduler");
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
quartzScheduler.setJobFactory(jobFactory);
quartzScheduler.setQuartzProperties(schedulingProperties);
return quartzScheduler;
}
上面的工作就像一个魅力。问题是 Quartz 配置没有使用 Flyway 自动装配 bean。它只需要在 Quartz 调度程序之前创建这个 bean。
所以理想的配置是:
数据库部分:
@Profile("!dbClean")
@Bean(name = "flyway", initMethod = "migrate")
public Flyway flywayNotADestroyer() {
Flyway flyway = new Flyway();
flyway.setDataSource(dataSource());
flyway.setInitOnMigrate(true);
return flyway;
}
@Profile("dbClean")
@Bean(name = "flyway", initMethod = "migrate")
public Flyway flywayTheDestroyer() {
Flyway flyway = new Flyway();
flyway.setDataSource(dataSource());
flyway.setInitOnMigrate(true);
flyway.clean();
return flyway;
}
石英部分:
@Bean
@DependsOn({"flyway"})
public SchedulerFactoryBean quartzScheduler() throws SchedulerException {
SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();
quartzScheduler.setDataSource(dataSource);
quartzScheduler.setTransactionManager(transactionManager);
quartzScheduler.setOverwriteExistingJobs(true);
quartzScheduler.setSchedulerName("mysuperduperthegratest-quartz-scheduler");
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
quartzScheduler.setJobFactory(jobFactory);
quartzScheduler.setQuartzProperties(schedulingProperties);
return quartzScheduler;
}
问题是最后一个配置不起作用。从未创建过任何一种flyway bean。我不知道为什么。回想起我使用 xml 配置时,我记得在不同的配置文件中可以有两个具有相同名称的 bean。它奏效了。我在这里做错了什么,或者这可能是 Spring 本身的一些错误?通常我自己调试 Spring,但带有 @Configuration 逻辑的 Spring 部分对我来说是一个绿色文件,我现在不能在上面浪费时间。