2

I have a configuration file with fields where should values be injected. I have one property:

@Value("${other.app.start.script:}")
private String startScript;

The value which injects in this property is smth like this:

/app/${version}/otherAppStarter.bat

So, Spring is trying to resolve ${version} when Context is starting. But I need this value be resolved at other time during some processes will run. And the ${version} might be changed during the main app is working.

Is there any way to tell Spring not to resolve ${version} placeholder. I can change ${version} to something like #[version] then Spring will not resolve this placeholder, but maybe there is the way to use some native Spring features.

Thank You!

migAlex
  • 273
  • 3
  • 16
  • Does this answer your question? [Escape property reference in Spring property file](https://stackoverflow.com/questions/13162346/escape-property-reference-in-spring-property-file) – SatheeshJM Jun 19 '21 at 15:03

1 Answers1

1

You can register a static bean which extends PropertySourcesPlaceholderConfigurer and override its method convertPropertyValue.

public class MyPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer {

    @Override
    protected String convertPropertyValue(String originalValue) {
        if (originalValue.contains("${version}")) {
            return originalValue;
        }

        return super.convertPropertyValue(originalValue);
    }
}

In case, you are using a Java configuration via @PropertySource, you will need to override the method doProcessProperties as well, as described in Spring Jira SPR-8928:

@Override
protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
                                   StringValueResolver valueResolver) {

    super.doProcessProperties(beanFactoryToProcess,
            new StringValueResolver() {
                @Override
                public String resolveStringValue(String strVal) {
                    return convertPropertyValue(valueResolver.resolveStringValue(strVal));
                }
            });
}

An example of Java configuration could look like this:

@Configuration
@PropertySource("classpath:saml/saml.properties")
public class MyConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer myPlaceholderConfigurer() {
        return new MyPlaceholderConfigurer();
    }
}
Vít Kotačka
  • 1,472
  • 1
  • 15
  • 40