How to run environment specific code in Spring Boot?

Let’s say you want to run environment specific code in your Spring Boot application.

Say if the environment is local , you get data from a temporary cache and if the environment is anything higher you get it from a third party service.

How to do this?

You can specify the environment to be activated by setting the below property in your properties file:

spring.profiles.active = local

This is usually provided in application.properties (/yml) file.

But it can be overridden while running the spring boot application from command line.

The one set in command line takes precedence over the one set in application properties file.

Now , having set the active profile how can we execute environment specific code inside the applicaiton.

By using the ‘Environment’ bean provided by Spring .

First inject the environment bean in your class:

	@Autowired
	private Environment environment;

Then check for the active profiles. If it contains local execute local specific code else execute the other:

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

			// execute local specific code.
		} else {

			// execute code for higher environments.
		}

The active profiles are returned by environment.getActiveProfiles() which is a string array. I have converted it to an arraylist in the above code and then checked if it contains “local” environment.

That’s it!


Posted

in

,

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading