您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Spring Boot在启动时将示例数据插入数据库

Spring Boot在启动时将示例数据插入数据库

您可以捕获ApplicationReadyEvent然后插入演示数据,例如:

@Component
public class DemoData {

    @Autowired
    private final EntityRepository repo;

    @EventListener
    public void appReady(ApplicationReadyEvent event) {

        repo.save(new Entity(...));
    }
}

或者,您可以实现CommandLineRunnerApplicationRunner在应用程序完全启动时加载演示数据:

@Component
public class DemoData implements CommandLineRunner {

    @Autowired
    private final EntityRepository repo;

    @Override
    public void run(String...args) throws Exception {

        repo.save(new Entity(...));
    }
}

@Component
public class DemoData implements ApplicationRunner {

    @Autowired
    private final EntityRepository repo;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        repo.save(new Entity(...));
    }
}

或者甚至像在您的Application(或其他“ config”)类中的Bean一样实现它们:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner demoData(EntityRepository repo) {
        return args -> {

            repo.save(new Entity(...));
        }
    }
}
Java 2022/1/1 18:23:39 有565人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶