spring 노트 - PropertySourcesPropertyResolver

2939 단어

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

좋은 웹페이지 즐겨찾기