【问题标题】:SpringBoot: Create document in mongodb on startup if not existsSpring Boot:如果不存在,则在启动时在 mongodb 中创建文档
【发布时间】:2021-12-30 15:40:02
【问题描述】:

我在 SpringBoot 和 Mongodb 上有一个小服务作为数据库。 我需要能够在启动时创建一个包含一个文档(非常基本:id、name、status)的小集合。如果不存在,则类似于 sql create table,但用于 mongo。我怎么做? 我试图初始化文档属性中的值,但没有帮助。 目前,集合和文档只有在我使用 API 添加时才会出现。

【问题讨论】:

    标签: mongodb spring-boot spring-data-mongodb mongotemplate aws-documentdb


    【解决方案1】:

    您可以利用 spring 内部事件机制。 当您的应用程序准备就绪时,spring 会触发事件ApplicationReadyEvent

    您可以收听此事件并初始化您的收藏:

    @Component
    public class DataInit implements ApplicationListener<ApplicationReadyEvent> {
    
        private final MyRepository myRepository;
    
        public DataInit(MyRepository myRepository) {
            this.myRepository = myRepository;
        }
    
        @Override
        public void onApplicationEvent(ApplicationReadyEvent event) {
            // init data
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可能想要使用 ApplicationRunnerCommandLineRunner 之类的东西,它们可以定义为 bean。

      例子:

      @SpringBootApplication
      public class MyApplication {
      
          public static void main(String[] args) {
              SpringApplication.run(MyApplication .class, args);
          }
      
          @Bean
          public CommandLineRunner initialize(MyRepository myRepository) {
      
              return args -> {
                  // Insert elements into myRepository 
              };
          }
      }
      

      CommandLineRunnerApplicationRunner 都是函数式接口,因此我们可以为它们使用 lambda。 Spring Boot 将在应用程序启动时执行它们。

      【讨论】:

        猜你喜欢
        • 2019-08-04
        • 1970-01-01
        • 2023-02-22
        • 2021-09-12
        • 1970-01-01
        • 2019-02-16
        • 2016-10-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多