Create a seeder on Spring Boot

Create seeders using Spring Boot:

package com.yamicode.seeder.seeders;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MainSeeder implements CommandLineRunner {

    @Autowired
    MySeeder mySeeder;

    @Override
    public void run(String... args) throws Exception {
      // execute the code you want to or just call an other function that will handle that like the following
      mySeeder.run();
    }
}

Examples:

the following java code create a folder on the app run.

package com.yamicode.seeder.seeders;

import java.io.File;
import org.springframework.stereotype.Component;

@Component
public class MySeeder{

    public void run(){
      new File("yamicode").mkdirs();
    }
}

the following java code insert and create a default user object into database to use on first run off the app.

package com.yamicode.seeder.seeders;

import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
//import your user repository

@Component
public class MySeeder{
    @Autowired
    private UserRepository userRepository;

    public void run(){
        User oldUser =  userRepository.findByEmail("admin@yamicode.com");
        if(oldUser==null){
          User user = new User();
          user.setEmail("admin@yamicode.com");
          user.setFirstname("yami");
          user.setLastname("code");
          userRepository.save(user);
        }
    }
}