Skip to content

Instantly share code, notes, and snippets.

Last active December 31, 2020 14:50
What would you like to do?
Spring Boot Initialize Local Test Data on Startup
/** Shows how to use code to init data instead of using data.sql or import.sql with Spring Boot */
@Profile({"local", "test"})
@RequiredArgsConstructor //Lombok magic to autowire the final fields (optional)
public class LocalDataSetup implements ApplicationRunner {
private final MyObjectRepository myObjectRepository;
public void run(ApplicationArguments args) {
if (myObjectRepository.count() == 0) { MyObject("abc", "123")); MyObject("def", "456")); MyObject("xyz", "789"));
//Yeah imports at the bottom look weird, but cleanup the gist
import com.sheetsj.entity.MyObject;
import com.sheetsj.repository.MyObjectRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment