How to fetch the in my springboot controller class that what is the environment , like if it is dev or UAT or prod?
Assistant
In a Spring Boot application, you can determine the active profile (e.g., dev, UAT, prod) from your controller class using the annotation or the interface. Here are a couple of ways to achieve that:
@Value
Environment
Option 1: Using @Value Annotation
You can inject the active profile using the @Value annotation. Spring allows you to fetch the active profile with the property spring.profiles.active.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@Value("${spring.profiles.active:defaultProfile}")
private String activeProfile;
@GetMapping("/environment")
public String getEnvironment() {
return "Active profile: " + activeProfile;
}
}
In this example, if you don't set any active profile, it defaults to "defaultProfile".
Option 2: Using Environment Interface
You can also inject the Environment to get more detailed information about the environment settings.
In this example, the getActiveProfiles() method returns an array of active profile names, which you can join into a string for display.
Summary
Use @Value for a simple injection of the active profile.
Use the Environment interface if you need more complex environment property access or multiple active profiles.
Setting Active Profiles
You can set the active profile in several ways:
In application.properties or application.yml, you can set:
spring.profiles.active=dev
As a command-line argument when starting your application:
-Dspring.profiles.active=prod
Set it as an environment variable:
export SPRING_PROFILES_ACTIVE=uat
With this setup in place, your Spring Boot application will be aware of the current active profile, and your controller can provide this information when queried.