我在 SpringBoot 和 Mongodb 上有一個小服務作為資料庫。我需要能夠在啟動時用一個檔案(非常基本的:id、name、status)創建一個小集合。如果不存在,則模擬 sql 創建表,但用于 mongo。我怎么做?我嘗試初始化檔案屬性中的值,但沒有幫助。目前,僅當我使用 API 添加它時才會出現集合和檔案。
uj5u.com熱心網友回復:
您可能想要使用類似ApplicationRunner或CommandLineRunner可以定義為 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
};
}
}
這兩個CommandLineRunner和ApplicationRunner是功能介面,所以我們可以使用lambda他們。Spring Boot 將在應用程式啟動時執行它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/362788.html
標籤:MongoDB 弹簧靴 spring-data-mongodb 蒙戈模板 aws-documentdb
上一篇:無法在Java中獲得類似的結果,因為CryptoJS.HmacSHA256在JavaScript中產生了結果
下一篇:Springboot查詢錯誤:價格上的運算子SIMPLE_PROPERTY需要標量引數,在方法publicabstractorg.Page中找到介面java.utilList
