Last active
December 31, 2020 14:50
-
-
Save jeffsheets/e018277e0ba2257c7d4b6c3c9767b1dd to your computer and use it in GitHub Desktop.
Spring Boot Initialize Local Test Data on Startup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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