您可以捕获ApplicationReadyEvent然后插入演示数据,例如:
@Component
public class DemoData {
@Autowired
private final EntityRepository repo;
@EventListener
public void appReady(ApplicationReadyEvent event) {
repo.save(new Entity(...));
}
}
或者您可以实现CommandLineRunner或ApplicationRunner,以在应用程序完全启动时加载演示数据:
@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(...));
}
}
甚至可以像你的应用程序(或其他’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(...));
}
}
}