Skip to content

Instantly share code, notes, and snippets.

Embed
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 */
@Component
@Profile({"local", "test"})
@RequiredArgsConstructor //Lombok magic to autowire the final fields (optional)
public class LocalDataSetup implements ApplicationRunner {
private final MyObjectRepository myObjectRepository;
@Override
public void run(ApplicationArguments args) {
if (myObjectRepository.count() == 0) {
myObjectRepository.save(new MyObject("abc", "123"));
myObjectRepository.save(new MyObject("def", "456"));
myObjectRepository.save(new 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