我正在创建一个使用 Quartz 的计时器应用程序,还使用 spring 从 schema.sql 文件初始化我的数据库。当应用程序启动时,我希望在创建 Scheduler bean 之前初始化 DB。
@Bean
public Scheduler scheduler() throws SchedulerException {
Scheduler scheduler;
final StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory("application.properties");
stdSchedulerFactory.initialize();
scheduler = stdSchedulerFactory.getScheduler();
scheduler.start();
return scheduler;
}
Scheduler bean 位于 TimerConfiguration.java 中,它被添加到 TimerApplication 中,如
@SpringBootApplication
@Import({TimerConfiguration.class})
public class TimerApplication {
有办法实现吗?
最佳答案
@DependsOn
注解指定了一个 bean,它应该在另一个 bean 初始化之后被初始化。
建议在注解中设置等待bean的名字作为值。
在你的例子中是 @DependsOn("datasource")
。
来自文档的更多信息:
Beans on which the current bean depends. Any beans specified are guaranteed to be created by the container before this bean. Used infrequently in cases where a bean does not explicitly depend on another through properties or constructor arguments, but rather depends on the side effects of another bean's initialization.
May be used on any class directly or indirectly annotated with Component or on methods annotated with Bean.
关于java - 创建bean之前的数据库初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40904104/