Search code examples
springspring-bootjava-17spring-context

Spring override application.properties without using spring.config.location


I am trying to override some properties defined in my packaged application.properties file:

my_name=initialValue

But I can't retrieved the external value of the property my_name. Due to my application being deployed in a Tomcat with several others apps I can't use spring.config.location as it might affect other application deployed there.

I've attempted the following approach:

  1. Loading properties with @Configuration as:
@Configuration
@PropertySources({
       @PropertySource("classpath:application.properties"),
       @PropertySource("file:${external_dir}/my_externalfile.properties"),
}
)
public class AppConfig {

   @Value("${my_name}")
   private String myName;

   @Value("${other}")
   private String other;
}

  1. I've also declared a bean as: @Bean public static PropertySourcesPlaceholderConfigurer PropertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer();} Even though the property my_name holds the default value other properties not defined in application.properties are loaded from the external file value. Is this behavior normal? I was expecting to simply been able to override the value.

I manage to get around that by declaring a placeholder in the application.properties as:

my_name=${var_external_placeholder}

And in the external file:

var_external_placeholder=ExternalValue

According to spring docs, Is this possible? It looks like Config data will override the value defined by @PropertySource and if not what is the purpose of defining @PropertySource

2. @PropertySource annotations on your @Configuration classes. Please note that such property sources are not added to the Environment until the application context is being refreshed. This is too late to configure certain properties such as logging.* and spring.main.* which are read before refresh begins.

3.Config data (such as application.properties files).

Solution

  • Can't you just make your code look for var_external_placeholder directly ? Overriding is not a good idea, a variable should be defined only once within the properties as there is not guarantee of which one will be picked up.

    You can also put a predefined value with this syntax if you want a default value, see stackoverflow.com/q/53820716/11758130