Skip to content

Instantly share code, notes, and snippets.

@jeffsheets
Last active December 31, 2020 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffsheets/e018277e0ba2257c7d4b6c3c9767b1dd to your computer and use it in GitHub Desktop.
Save jeffsheets/e018277e0ba2257c7d4b6c3c9767b1dd to your computer and use it in GitHub Desktop.
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