Search code examples
javaspring-boot

If condition based on Activeprofile


I am trying to run a query in H2 in-memory for testing purposes. Due to H2 limitation, certain syntax does not work. I am looking to change the syntax based on @Activeprofile in Spring Boot. My code would look something like this:

if (@Activeprofile("Test")) {
    query = "something for test"
} else {
    query = "something for prod/stage" 
}

Is this possible? Any help appreciated.


Solution

  • You have to inject an Environment Bean into your code.

    Like this:

    @Autowired
    private Environment environment;
    

    You can then use the .getActiveProfiles() method.

    if (Arrays.asList(environment.getActiveProfiles()).contains("...") {
        ...
    }
    

    More on this can be found here.