Spring Boot insert sample data into database upon startup

后端 未结 3 1055
广开言路
广开言路 2020-12-15 08:19

What is the right way for creating test data upon server startup and inserting them into the database (I\'m using a JPA/JDBC backed Postgres instance).

Preferably in

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 08:57

    You can catch ApplicationReadyEvent then insert demo data, for example:

    @Component
    public class DemoData {
    
        @Autowired
        private final EntityRepository repo;
    
        @EventListener
        public void appReady(ApplicationReadyEvent event) {
    
            repo.save(new Entity(...));
        }
    }
    

    Or you can implement CommandLineRunner or ApplicationRunner, to load demo data when an application is fully started:

    @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(...));
        }
    }
    

    Or even implement them like a Bean right in your Application (or other 'config') class:

    @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(...));
            }
        }
    }
    

提交回复
热议问题