1

In my spring boot application I have made info-local.properties and info-dev.properties How do I access the correct one based on current active profile?

2 Answers2

1

Environment-Specific Properties File

The naming convention of spring-boot properties file is application-<profile>.properties to get it automatically read without any extra line of code. You should rename your properties file as application-local.properties and application-dev.properties.

Click here for reference.

Set Profiles

There are various ways to activate any specific profile. The easiest ways are:

  1. JVM System Parameter : Add -Dspring.profiles.active=dev to VM args while running.

  2. Application Properties : Add spring.profiles.active=dev in the common application.properties file .

Click here for another way around.

Load properties manually

@Configuration
@PropertySource("classpath:info-${envTarget}.properties")
public class PropertiesWithJavaConfig {
    //...
}

${envTarget} will get resolved by the active profile, and it will load the correct info-xxx properties into PropertiesWithJavaConfig. Click here for reference.

sas
  • 512
  • 2
  • 8
  • Thanks. How do u do that for custom yaml file that is not application yml. Look like spring only auto append the profile to properties and yaml whose names are application. Wonder why it can't do that for custom name properties/yaml – Nick Wills Feb 18 '22 at 05:54
  • Cos @propertysource don't support yaml, if I not wrong – Nick Wills Feb 18 '22 at 05:55
-1

Spring Profiles provide a way to segregate parts of your application configuration and make it only available in certain environments.

  • A simple solution for you would be to just start the application like this:

    --spring.profiles.active=local,dev

  • You can also annotate your main config class specifying what profile you want:

    @Configuration @Profile("production") class MainConfig{.. }

  • You can programmatically set active profiles by calling SpringApplication.setAdditionalProfiles(...) before your application runs. It is also possible to activate profiles using Spring’s ConfigurableEnvironment interface.

I will also leave a link with an example for this: Spring profiles example

Opri
  • 590
  • 2
  • 11
  • The main issue is to load an `info-XXX.properties` file, which this answer doesn't help with. Not useful. – Andreas Jun 29 '21 at 14:56