1. Overview

In this article, We will learn Spring boot get active profile or How to check current active profiles in spring boot at runtime.

To get current active profiles need to Autowire  org.springframework.core.env.Environment. We can Autowire inside ServiceComponent , Controller or any other place where spring allowed Autowire. Environment has getActiveProfiles() method will return String Array Of all current active profiles in the application.

Here we have printed all active profiles in the application, We can also write our custom code based on active profiles like for the testing environment or production environment may require writing different code. Here is an article for spring boot profile example.

2. Example

In this example, We have determined active profile in spring boot.

package com.javadeveloperzone.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by JavaDeveloperZone on 28-04-2018.
 */
@RestController
public class ProfileCheckController {
    @Autowired
    private org.springframework.core.env.Environment environment;
    @GetMapping("/checkProfile")
    public String[] checkProfile() {
        String[] activeProfiles = environment.getActiveProfiles();      // it will return String Array of all active profile.  
        for(String profile:activeProfiles) {
            System.out.print(profile);
        }
        return activeProfiles;
    }
}

Output

Spring boot get active profile - output

Spring boot get active profile – output

3. References

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *