1

I am running a jar file and I use -Dspring.profiles.active=. How do I get the running profile name during runtime. I want to use that in my code and have some changes based on the profile. Is there any way to get that?

kkk
  • 51
  • 3

1 Answers1

5

You need to inject Environment reference into your class, e.g.:

@Autowired
private Environment environment;

You can then call getActiveProfiles() method to get the profiles (documentation here). This is what the docs says:

Returns the set of profiles explicitly made active for this environment. Profiles are used for creating logical groupings of bean definitions to be registered conditionally, for example based on deployment environment. Profiles can be activated by setting "spring.profiles.active" as a system property or by calling ConfigurableEnvironment.setActiveProfiles(String...).

Also, Environment bean is created by Spring so you don't need to @Bean it explicitly in your application.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
  • Thank you @Darshan. Got it . For default profile it is @Value("${spring.profiles.active:default}") private String activeProfile; It worked now as expected – kkk Feb 14 '19 at 10:51