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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s