Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 951
gklaxman Avatar asked Feb 24 '26 13:02

gklaxman


2 Answers

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.

like image 152
Niby Avatar answered Feb 27 '26 02:02

Niby


You can access the profiles by injecting the property spring.profiles.active:

@Value("${spring.profiles.active}")
private String activeProfile;

Here, the activeProfile variable will contain the name of the profile that is currently active, and if there are several, it’ll contain their names separated by a comma.

like image 23
Vinicius Avatar answered Feb 27 '26 02:02

Vinicius