I have a Java lib which is based on Spring Boot. In my case I need to resolve placeholders which start with something.*
in my own way before this property will be resolved by some Spring Property Resolver. For example:
application.properties:
spring.datasource.url="${something.url}"
So this placeholder is matching my something.*
pattern and I want to replace it with specific
word before Spring will try to resolve it. Where can I do it so I can avoid creating system properties with System.setProperty
?
Here is my attempts on achieving it:
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.util.StringValueResolver;
import java.util.Properties;
public class MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
throws BeansException {
StringValueResolver valueResolver = new ReloadablePlaceholderResolvingStringValueResolver(props);
this.doProcessProperties(beanFactoryToProcess, valueResolver);
}
private class ReloadablePlaceholderResolvingStringValueResolver
implements StringValueResolver {
private final PropertyPlaceholderHelper helper;
private final ReloadablePropertyPlaceholderConfigurerResolver resolver;
public ReloadablePlaceholderResolvingStringValueResolver(Properties props) {
this.helper = new MyPropertyPlaceholderHelper(placeholderPrefix, placeholderSuffix, valueSeparator, ignoreUnresolvablePlaceholders);
this.resolver = new ReloadablePropertyPlaceholderConfigurerResolver(props);
}
@Override
public String resolveStringValue(String strVal) throws BeansException {
String value = this.helper.replacePlaceholders(strVal, this.resolver);
return (value.equals(nullValue) ? null : value);
}
}
private class ReloadablePropertyPlaceholderConfigurerResolver
implements PropertyPlaceholderHelper.PlaceholderResolver {
private Properties props;
private ReloadablePropertyPlaceholderConfigurerResolver(Properties props) {
this.props = props;
}
@Override
public String resolvePlaceholder(String placeholderName) {
return MyPropertyPlaceholderConfigurer.this.resolvePlaceholder(placeholderName, props, SYSTEM_PROPERTIES_MODE_FALLBACK);
}
}
}
Initializing bean:
@Bean
public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new MyPropertyPlaceholderConfigurer();
}
Getting resolved property:
@RestController
public class MainController {
@Autowired
private Environment environment;
@GetMapping("/getEnvProeprty")
public String getEnvironmentName() {
return environment.getProperty("spring.datasource.url");
}
}