您可以捕获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(...));
}
}
或者甚至像在您的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(...));
}
}
}