spring笔记-PropertySourcesPropertyResolver

1.PropertySourcesPropertyResolver

PropertySources+PropertyPlaceholderHelper的结合,

即PropertySources是数据源,PropertyPlaceholderHelper具备解析占位符的功能

资源文件

name=hello
age=10,${name}
encoding=utf-8
name2=${name}

测试代码

    @Test
    public void test1() throws Exception {
        //省略propertySources

        PropertyResolver propertyResolver = new PropertySourcesPropertyResolver(getPropertySources());

        System.out.println(propertyResolver.getProperty("name"));
        System.out.println(propertyResolver.getProperty("name2"));
        System.out.println(propertyResolver.getProperty("encoding"));
        System.out.println(propertyResolver.getProperty("no", "default"));
        System.out.println(propertyResolver.resolvePlaceholders("must be encoding ${encoding}"));  //输出must be encoding gbk
    }

结果

hello
hello
utf-8
default
must be encoding utf-8

2.StandardEnvironment

其也实现了PropertyResolver接口,实现了与PropertySourcesPropertyResolver一致的功能

其内部提供了一个propertySources属性

···
private final MutablePropertySources propertySources = new MutablePropertySources(this.logger);

private final ConfigurablePropertyResolver propertyResolver =
        new PropertySourcesPropertyResolver(this.propertySources);


/**
 * Create a new {@code Environment} instance, calling back to
 * {@link #customizePropertySources(MutablePropertySources)} during construction to
 * allow subclasses to contribute or manipulate {@link PropertySource} instances as
 * appropriate.
 * @see #customizePropertySources(MutablePropertySources)
 */
public AbstractEnvironment() {
    customizePropertySources(this.propertySources);
    if (logger.isDebugEnabled()) {
        logger.debug("Initialized " + getClass().getSimpleName() + " with PropertySources " + this.propertySources);
    }
}

···

可以通过重写customizePropertySources方法来更改数据源

public class StandardEnvironment extends AbstractEnvironment {

    /** System environment property source name: {@value} */
    public static final String SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME = "systemEnvironment";

    /** JVM system properties property source name: {@value} */
    public static final String SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME = "systemProperties";

    @Override
    protected void customizePropertySources(MutablePropertySources propertySources) {
        propertySources.addLast(new MapPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));
        propertySources.addLast(new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));
    }

}

参考:
https://blog.csdn.net/weixin_39165515/article/details/77497682

你可能感兴趣的:(spring笔记-PropertySourcesPropertyResolver)