如何解决在spring环境属性中以“something”开头的所有占位符?

时间:2018-02-05 15:52:38

标签: java spring

我有一个基于Spring Boot的Java库。在我的情况下,我需要以自己的方式解决以something.*开头的占位符,然后由一些Spring Property Resolver解析此属性。例如:

application.properties

spring.datasource.url="${something.url}"

因此,此占位符与我的something.*模式匹配,我希望在Spring试图解决之前用specific字替换它。我在哪里可以这样做,以便我可以避免使用System.setProperty创建系统属性?

以下是我尝试实现它的尝试:

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);
        }
    }
}

初始化bean:

@Bean
public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
    return new MyPropertyPlaceholderConfigurer();
}

获得解决的财产:

@RestController
public class MainController {

    @Autowired
    private Environment environment;

    @GetMapping("/getEnvProeprty")
    public String getEnvironmentName() {
        return environment.getProperty("spring.datasource.url");
    }
}

0 个答案:

没有答案