Search code examples
springapplication.properties

Use empty string as default value for a property so that it can be concatenated with other strings to form a value


In my application.properties file, I have the following property which is formed concatenating 3 properties:

eureka.instance.appname=${spring.application.name}${spring.profiles.active}${variant:}

My intent is that when the variant property is not initialized the eureka.instance.appname should be formed by concatenating the default empty string for the variant property so that the value would be ${spring.application.name}${spring.profiles.active} alone.

But the final string is not formed properly if I define it in the above specified format. I could not find a way to assign an empty string as a default value for variant. When I use ${variant:''}, while spring.application.name is SERVICE and spring.profiles.active is DEV and variant is not assigned a value, the default value ' is picked, I get a eureka.instance.appname as SERVICEDEV''.

What I tried so far:

eureka.instance.appname=${spring.application.name}${spring.profiles.active}${variant:} 

does not work and probably crashes.

eureka.instance.appname=${spring.application.name}${spring.profiles.active}${variant:''} 

gives SERVICEDEV'' where spring.application.name is SERVICE and spring.profiles.active is DEV and variant is not assigned a value


Solution

  • eureka.instance.appname=${spring.application.name}${spring.profiles.active}${variant:} this works for me.

    Other Way: You can have your PropertySourcesPlaceholderConfigurer check the value of variant. If null then it can change it to empty string.

        @Bean
        public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
            return new PropertySourcesPlaceholderConfigurer() {
    
                @Override
                public void setEnvironment(Environment environment) {
                    if (environment instanceof ConfigurableEnvironment && environment.getProperty("variant") == null) {
                        ConfigurableEnvironment env = (ConfigurableEnvironment) environment;
                        env.getPropertySources().addLast(new MapPropertySource("Public key default", Collections.singletonMap("variant", "")));
                    }
    
                    super.setEnvironment(environment);
                }
            };
        }