Home > OS >  How to prevent CommandLineRunner run() method exectution based on active spring profile being used?
How to prevent CommandLineRunner run() method exectution based on active spring profile being used?

Time:10-12

I am writing Springboot app with Spring Data JPA and I use two application.properties defining development and production profiles.

My production profile uses real database.

My development profile uses an H2 database.

I determine which profile to use be setting spring.profiles.active flag in application.properties file.

The app also uses CommandLineRunner to pre-populate my H2 database with some data.

I don't want my CommandLineRunner to do same for production database.

How do I ensure CommandLineRunner will execute only in my development environment (when I set active profile to be development profile with spring.profiles.active=development)?

All google is giving me is the way to do same for tests but I dont want that. I want to be able to prevent CommandLineRunner from executing its run() method based on current spring profile.

CodePudding user response:

Just add a development profile annotation to your runner. This way the runner will only run when the active profile(s) includes development

@Component
@Profile("development")
public class H2Runner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        // Code here
    }
}
  • Related