Spring 使用CommandLineRunner准备数据&@施工后

Spring 使用CommandLineRunner准备数据&@施工后,spring,spring-boot,Spring,Spring Boot,我需要将文本文件中的数据填充到关系数据库中,并使用数据库中的数据来构建数据结构Tire。数据库是基于内存的数据库 作为常规方法,我在@SpringBootApplication类的CommandLineRunner方法中有数据填充代码,在服务类的@PostConstruct方法中有数据检索代码。然而,这并不像我想的那样有效,因为@PostConstruct方法是在CommandLineRunner之前执行的 为了解决这个问题,我还将数据检索代码移动到CommandLineRunner方法。但是,

我需要将文本文件中的数据填充到关系数据库中,并使用数据库中的数据来构建数据结构Tire。数据库是基于内存的数据库

作为常规方法,我在@SpringBootApplication类的CommandLineRunner方法中有数据填充代码,在服务类的@PostConstruct方法中有数据检索代码。然而,这并不像我想的那样有效,因为@PostConstruct方法是在CommandLineRunner之前执行的

为了解决这个问题,我还将数据检索代码移动到CommandLineRunner方法。但是,这种方法会创建代码耦合,因为数据结构只在服务类内部使用。我可以想到的另一种方法是对数据结构进行惰性数据初始化。由于数据量大,接近110k条目,数据结构使用的第一次运行时间将非常缓慢


有更好的方法吗?

您可以利用应用程序启动事件:

   // you can put this in any wired class or even in the Application class
    @EventListener
    public void onApplicationEvent(ContextRefreshedEvent event) {
         //Now you are sure Command line runner is done. 
     }

可能使用另一个
CommandLineRunner
来检索数据,并使用order注释@order。或者另一种方法是使用spring提供的应用程序启动事件,检查下面的答案。谢谢您的建议。在这种情况下,我将尝试使用异步事件。