Java 类org.springframework.core.env.MutablePropertySources 实例源码

项目:azure-spring-boot    文件:KeyVaultEnvironmentPostProcessorHelper.java   
public void addKeyVaultPropertySource() {
    final String clientId = getProperty(environment, Constants.AZURE_CLIENTID);
    final String clientKey = getProperty(environment, Constants.AZURE_CLIENTKEY);
    final String vaultUri = getProperty(environment, Constants.AZURE_KEYVAULT_VAULT_URI);

    final long timeAcquiringTimeoutInSeconds = environment.getProperty(
            Constants.AZURE_TOKEN_ACQUIRE_TIMEOUT_IN_SECONDS, Long.class, 60L);

    final KeyVaultClient kvClient = new KeyVaultClient(
            new AzureKeyVaultCredential(clientId, clientKey, timeAcquiringTimeoutInSeconds));

    try {
        final MutablePropertySources sources = environment.getPropertySources();
        final KeyVaultOperation kvOperation = new KeyVaultOperation(kvClient, vaultUri);

        if (sources.contains(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) {
            sources.addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
                    new KeyVaultPropertySource(kvOperation));
        } else {
            sources.addFirst(new KeyVaultPropertySource(kvOperation));
        }

    } catch (Exception ex) {
        throw new IllegalStateException("Failed to configure KeyVault property source", ex);
    }
}
项目:iBase4J-Common    文件:Configs.java   
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    // 此处可以http方式 到配置服务器拉取一堆公共配置+本项目个性配置的json串,拼到Properties里
    // ......省略new Properties的过程
    MutablePropertySources propertySources = environment.getPropertySources();
    // addLast 结合下面的 getOrder() 保证顺序 读者也可以试试其他姿势的加载顺序
    try {
        Properties props = getConfig(environment);
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String value = props.getProperty(keyStr);
            if ("druid.writer.password,druid.reader.password".contains(keyStr)) {
                String dkey = props.getProperty("druid.key");
                dkey = DataUtil.isEmpty(dkey) ? Constants.DB_KEY : dkey;
                value = SecurityUtil.decryptDes(value, dkey.getBytes());
                props.setProperty(keyStr, value);
            }
            PropertiesUtil.getProperties().put(keyStr, value);
        }
        propertySources.addLast(new PropertiesPropertySource("thirdEnv", props));
    } catch (IOException e) {
        logger.error("", e);
    }
}
项目:micrometer    文件:MetricsEnvironmentPostProcessor.java   
private void addDefaultProperty(ConfigurableEnvironment environment, String name,
                                String value) {
    MutablePropertySources sources = environment.getPropertySources();
    Map<String, Object> map = null;
    if (sources.contains("defaultProperties")) {
        PropertySource<?> source = sources.get("defaultProperties");
        if (source instanceof MapPropertySource) {
            map = ((MapPropertySource) source).getSource();
        }
    } else {
        map = new LinkedHashMap<>();
        sources.addLast(new MapPropertySource("defaultProperties", map));
    }
    if (map != null) {
        map.put(name, value);
    }
}
项目:holon-core    文件:DefaultEnvironmentConfigPropertyProvider.java   
@Override
public Stream<String> getPropertyNames() throws UnsupportedOperationException {
    List<String> names = new LinkedList<>();
    if (ConfigurableEnvironment.class.isAssignableFrom(getEnvironment().getClass())) {
        MutablePropertySources propertySources = ((ConfigurableEnvironment) getEnvironment()).getPropertySources();
        if (propertySources != null) {
            Iterator<PropertySource<?>> i = propertySources.iterator();
            while (i.hasNext()) {
                PropertySource<?> source = i.next();
                if (source instanceof EnumerablePropertySource) {
                    String[] propertyNames = ((EnumerablePropertySource<?>) source).getPropertyNames();
                    if (propertyNames != null) {
                        names.addAll(Arrays.asList(propertyNames));
                    }
                }
            }
        }
    }
    return names.stream();
}
项目:oma-riista-web    文件:WebAppContextInitializer.java   
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    final ConfigurableEnvironment configurableEnvironment = applicationContext.getEnvironment();
    configurableEnvironment.setDefaultProfiles(Constants.STANDARD_DATABASE);

    final MutablePropertySources propertySources = configurableEnvironment.getPropertySources();

    AwsCloudRuntimeConfig.createPropertySource().ifPresent(awsPropertySource -> {
        propertySources.addLast(awsPropertySource);

        LOG.info("Using Amazon RDS profile");

        configurableEnvironment.setActiveProfiles(Constants.AMAZON_DATABASE);
    });

    LiquibaseConfig.replaceLiquibaseServiceLocator();
}
项目:spring4-understanding    文件:PropertySourceAnnotationTests.java   
@Test
public void withExplicitName() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(ConfigWithExplicitName.class);
    ctx.refresh();
    assertTrue("property source p1 was not added",
            ctx.getEnvironment().getPropertySources().contains("p1"));
    assertThat(ctx.getBean(TestBean.class).getName(), equalTo("p1TestBean"));

    // assert that the property source was added last to the set of sources
    String name;
    MutablePropertySources sources = ctx.getEnvironment().getPropertySources();
    Iterator<org.springframework.core.env.PropertySource<?>> iterator = sources.iterator();
    do {
        name = iterator.next().getName();
    }
    while(iterator.hasNext());

    assertThat(name, is("p1"));
}
项目:x-pipe    文件:SpringApplicationStarter.java   
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
    super.customizePropertySources(propertySources);
    propertySources.addFirst(new PropertySource<Object>("TestAppServerProperty"){

        @Override
        public Object getProperty(String name) {

            if(name.equals("server.port")){
                return String.valueOf(port);
            }
            return null;
        }

    });
}
项目:x-pipe    文件:TestMetaServer.java   
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
    super.customizePropertySources(propertySources);
    propertySources.addFirst(new PropertySource<Object>("TestAppServerProperty"){

        @Override
        public Object getProperty(String name) {

            if(name.equals("server.port")){
                return String.valueOf(serverPort);
            }
            return null;
        }

    });
}
项目:spring4-understanding    文件:PropertySourcesPlaceholderConfigurerTests.java   
@Test
@SuppressWarnings("serial")
public void explicitPropertySourcesExcludesLocalProperties() {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    bf.registerBeanDefinition("testBean",
            genericBeanDefinition(TestBean.class)
                .addPropertyValue("name", "${my.name}")
                .getBeanDefinition());

    MutablePropertySources propertySources = new MutablePropertySources();
    propertySources.addLast(new MockPropertySource());

    PropertySourcesPlaceholderConfigurer pc = new PropertySourcesPlaceholderConfigurer();
    pc.setPropertySources(propertySources);
    pc.setProperties(new Properties() {{
        put("my.name", "local");
    }});
    pc.setIgnoreUnresolvablePlaceholders(true);
    pc.postProcessBeanFactory(bf);
    assertThat(bf.getBean(TestBean.class).getName(), equalTo("${my.name}"));
}
项目:setaria    文件:ConfigValueBeanFactoryPostProcessor.java   
public void postProcess(ConfigurableListableBeanFactory beanFactory) {
    // 注册 Spring 属性配置
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    MutablePropertySources mutablePropertySources = new MutablePropertySources();
    mutablePropertySources.addLast(new PropertySource<String>(Configs.class.getName()) {
        @Override
        public String getProperty(String name) {
            return Configs.getString(name);
        }
    });
    configurer.setPropertySources(mutablePropertySources);
    configurer.postProcessBeanFactory(beanFactory);

    /*
     * 注册 @ConfigValue 处理器. ConfigValueBeanPostProcessor 实现了 ApplicationListener 接口, 不能使用
     * beanFactory.addBeanPostProcessor() 来注册实例.
     */
    beanFactory.registerSingleton(ConfigValueBeanPostProcessor.class.getName(),
            new ConfigValueBeanPostProcessor(beanFactory));
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:ConfigurationPropertiesBindingPostProcessor.java   
private PropertySources loadPropertySources(String[] locations,
        boolean mergeDefaultSources) {
    try {
        PropertySourcesLoader loader = new PropertySourcesLoader();
        for (String location : locations) {
            Resource resource = this.resourceLoader
                    .getResource(this.environment.resolvePlaceholders(location));
            String[] profiles = this.environment.getActiveProfiles();
            for (int i = profiles.length; i-- > 0;) {
                String profile = profiles[i];
                loader.load(resource, profile);
            }
            loader.load(resource);
        }
        MutablePropertySources loaded = loader.getPropertySources();
        if (mergeDefaultSources) {
            for (PropertySource<?> propertySource : this.propertySources) {
                loaded.addLast(propertySource);
            }
        }
        return loaded;
    }
    catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:ConfigFileApplicationListener.java   
public static void finishAndRelocate(MutablePropertySources propertySources) {
    String name = APPLICATION_CONFIGURATION_PROPERTY_SOURCE_NAME;
    ConfigurationPropertySources removed = (ConfigurationPropertySources) propertySources
            .get(name);
    if (removed != null) {
        for (PropertySource<?> propertySource : removed.sources) {
            if (propertySource instanceof EnumerableCompositePropertySource) {
                EnumerableCompositePropertySource composite = (EnumerableCompositePropertySource) propertySource;
                for (PropertySource<?> nested : composite.getSource()) {
                    propertySources.addAfter(name, nested);
                    name = nested.getName();
                }
            }
            else {
                propertySources.addAfter(name, propertySource);
            }
        }
        propertySources.remove(APPLICATION_CONFIGURATION_PROPERTY_SOURCE_NAME);
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:SpringApplication.java   
/**
 * Add, remove or re-order any {@link PropertySource}s in this application's
 * environment.
 * @param environment this application's environment
 * @param args arguments passed to the {@code run} method
 * @see #configureEnvironment(ConfigurableEnvironment, String[])
 */
protected void configurePropertySources(ConfigurableEnvironment environment,
        String[] args) {
    MutablePropertySources sources = environment.getPropertySources();
    if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) {
        sources.addLast(
                new MapPropertySource("defaultProperties", this.defaultProperties));
    }
    if (this.addCommandLineProperties && args.length > 0) {
        String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
        if (sources.contains(name)) {
            PropertySource<?> source = sources.get(name);
            CompositePropertySource composite = new CompositePropertySource(name);
            composite.addPropertySource(new SimpleCommandLinePropertySource(
                    name + "-" + args.hashCode(), args));
            composite.addPropertySource(source);
            sources.replace(name, composite);
        }
        else {
            sources.addFirst(new SimpleCommandLinePropertySource(args));
        }
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:CloudFoundryVcapEnvironmentPostProcessor.java   
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
        SpringApplication application) {
    if (CloudPlatform.CLOUD_FOUNDRY.isActive(environment)) {
        Properties properties = new Properties();
        addWithPrefix(properties, getPropertiesFromApplication(environment),
                "vcap.application.");
        addWithPrefix(properties, getPropertiesFromServices(environment),
                "vcap.services.");
        MutablePropertySources propertySources = environment.getPropertySources();
        if (propertySources.contains(
                CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
            propertySources.addAfter(
                    CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
                    new PropertiesPropertySource("vcap", properties));
        }
        else {
            propertySources
                    .addFirst(new PropertiesPropertySource("vcap", properties));
        }
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:PropertiesConfigurationFactoryParameterizedTests.java   
@Deprecated
private Foo bindFoo(final String values) throws Exception {
    Properties properties = PropertiesLoaderUtils
            .loadProperties(new ByteArrayResource(values.getBytes()));
    if (this.usePropertySource) {
        MutablePropertySources propertySources = new MutablePropertySources();
        propertySources.addFirst(new PropertiesPropertySource("test", properties));
        this.factory.setPropertySources(propertySources);
    }
    else {
        this.factory.setProperties(properties);
    }

    this.factory.afterPropertiesSet();
    return this.factory.getObject();
}
项目:spring-boot-concourse    文件:ConfigurationPropertiesBindingPostProcessor.java   
private PropertySources loadPropertySources(String[] locations,
        boolean mergeDefaultSources) {
    try {
        PropertySourcesLoader loader = new PropertySourcesLoader();
        for (String location : locations) {
            Resource resource = this.resourceLoader
                    .getResource(this.environment.resolvePlaceholders(location));
            String[] profiles = this.environment.getActiveProfiles();
            for (int i = profiles.length; i-- > 0;) {
                String profile = profiles[i];
                loader.load(resource, profile);
            }
            loader.load(resource);
        }
        MutablePropertySources loaded = loader.getPropertySources();
        if (mergeDefaultSources) {
            for (PropertySource<?> propertySource : this.propertySources) {
                loaded.addLast(propertySource);
            }
        }
        return loaded;
    }
    catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
项目:spring-boot-concourse    文件:ConfigFileApplicationListener.java   
public static void finishAndRelocate(MutablePropertySources propertySources) {
    String name = APPLICATION_CONFIGURATION_PROPERTY_SOURCE_NAME;
    ConfigurationPropertySources removed = (ConfigurationPropertySources) propertySources
            .get(name);
    if (removed != null) {
        for (PropertySource<?> propertySource : removed.sources) {
            if (propertySource instanceof EnumerableCompositePropertySource) {
                EnumerableCompositePropertySource composite = (EnumerableCompositePropertySource) propertySource;
                for (PropertySource<?> nested : composite.getSource()) {
                    propertySources.addAfter(name, nested);
                    name = nested.getName();
                }
            }
            else {
                propertySources.addAfter(name, propertySource);
            }
        }
        propertySources.remove(APPLICATION_CONFIGURATION_PROPERTY_SOURCE_NAME);
    }
}
项目:spring-boot-concourse    文件:SpringApplication.java   
/**
 * Add, remove or re-order any {@link PropertySource}s in this application's
 * environment.
 * @param environment this application's environment
 * @param args arguments passed to the {@code run} method
 * @see #configureEnvironment(ConfigurableEnvironment, String[])
 */
protected void configurePropertySources(ConfigurableEnvironment environment,
        String[] args) {
    MutablePropertySources sources = environment.getPropertySources();
    if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) {
        sources.addLast(
                new MapPropertySource("defaultProperties", this.defaultProperties));
    }
    if (this.addCommandLineProperties && args.length > 0) {
        String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
        if (sources.contains(name)) {
            PropertySource<?> source = sources.get(name);
            CompositePropertySource composite = new CompositePropertySource(name);
            composite.addPropertySource(new SimpleCommandLinePropertySource(
                    name + "-" + args.hashCode(), args));
            composite.addPropertySource(source);
            sources.replace(name, composite);
        }
        else {
            sources.addFirst(new SimpleCommandLinePropertySource(args));
        }
    }
}
项目:spring-boot-concourse    文件:CloudFoundryVcapEnvironmentPostProcessor.java   
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
        SpringApplication application) {
    if (CloudPlatform.CLOUD_FOUNDRY.isActive(environment)) {
        Properties properties = new Properties();
        addWithPrefix(properties, getPropertiesFromApplication(environment),
                "vcap.application.");
        addWithPrefix(properties, getPropertiesFromServices(environment),
                "vcap.services.");
        MutablePropertySources propertySources = environment.getPropertySources();
        if (propertySources.contains(
                CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
            propertySources.addAfter(
                    CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
                    new PropertiesPropertySource("vcap", properties));
        }
        else {
            propertySources
                    .addFirst(new PropertiesPropertySource("vcap", properties));
        }
    }
}
项目:spring-boot-concourse    文件:PropertiesConfigurationFactoryParameterizedTests.java   
@Deprecated
private Foo bindFoo(final String values) throws Exception {
    Properties properties = PropertiesLoaderUtils
            .loadProperties(new ByteArrayResource(values.getBytes()));
    if (this.usePropertySource) {
        MutablePropertySources propertySources = new MutablePropertySources();
        propertySources.addFirst(new PropertiesPropertySource("test", properties));
        this.factory.setPropertySources(propertySources);
    }
    else {
        this.factory.setProperties(properties);
    }

    this.factory.afterPropertiesSet();
    return this.factory.getObject();
}
项目:azure-spring-boot    文件:InitializerTest.java   
@Test
public void testAzureKvPropertySourceNotInitialized() {
    final MutablePropertySources sources =
            ((ConfigurableEnvironment) context.getEnvironment()).getPropertySources();

    assertFalse("PropertySources should not contains azurekv when enabled=false",
            sources.contains(Constants.AZURE_KEYVAULT_PROPERTYSOURCE_NAME));
}
项目:hevelian-activemq    文件:ReversePropertySourcesStandardServletEnvironmentTest.java   
@Test
public void customizePropertySources() {
    MutablePropertySources propertySources = new MutablePropertySources();
    ReversePropertySourcesStandardServletEnvironment env = new ReversePropertySourcesStandardServletEnvironment();
    env.customizePropertySources(propertySources);

    String[] sourceNames = { StandardServletEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
            StandardServletEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME,
            StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME,
            StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME };
    List<String> result = new ArrayList<>();
    propertySources.forEach(a -> result.add(a.getName()));
    Assert.assertArrayEquals(sourceNames, result.toArray());
}
项目:lams    文件:PropertySourcesPlaceholderConfigurer.java   
/**
 * {@inheritDoc}
 * <p>Processing occurs by replacing ${...} placeholders in bean definitions by resolving each
 * against this configurer's set of {@link PropertySources}, which includes:
 * <ul>
 * <li>all {@linkplain org.springframework.core.env.ConfigurableEnvironment#getPropertySources
 * environment property sources}, if an {@code Environment} {@linkplain #setEnvironment is present}
 * <li>{@linkplain #mergeProperties merged local properties}, if {@linkplain #setLocation any}
 * {@linkplain #setLocations have} {@linkplain #setProperties been}
 * {@linkplain #setPropertiesArray specified}
 * <li>any property sources set by calling {@link #setPropertySources}
 * </ul>
 * <p>If {@link #setPropertySources} is called, <strong>environment and local properties will be
 * ignored</strong>. This method is designed to give the user fine-grained control over property
 * sources, and once set, the configurer makes no assumptions about adding additional sources.
 */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    if (this.propertySources == null) {
        this.propertySources = new MutablePropertySources();
        if (this.environment != null) {
            this.propertySources.addLast(
                new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {
                    @Override
                    public String getProperty(String key) {
                        return this.source.getProperty(key);
                    }
                }
            );
        }
        try {
            PropertySource<?> localPropertySource =
                new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties());
            if (this.localOverride) {
                this.propertySources.addFirst(localPropertySource);
            }
            else {
                this.propertySources.addLast(localPropertySource);
            }
        }
        catch (IOException ex) {
            throw new BeanInitializationException("Could not load properties", ex);
        }
    }

    processProperties(beanFactory, new PropertySourcesPropertyResolver(this.propertySources));
    this.appliedPropertySources = this.propertySources;
}
项目:rmap    文件:KafkaPropertyUtils.java   
/**
 * Returns the property key/value pairs found in {@code sources} and returns them in a {@code Map}.  Only instances
 * of {@code EnumerablePropertySource} are considered.  If {@code sources} contains other types of
 * {@code PropertySource}, they will be ignored, and <em>not</em> included in the returned {@code Map}.
 * <p>
 * If {@code prefix} is provided, only properties that start with the supplied prefix will be included in the
 * returned {@code Map}.  If {@code strip} is {@code true} and {@code prefix} is non-null, the {@code prefix} will
 * be stripped from the property key in the returned {@code Map}.
 * </p>
 *
 * @param sources {@code MutablePropertySources} whose key/value pairs are enumerated and placed into the returned
 *                {@code Map}
 * @param prefix only include properties whose key starts with the supplied prefix, may be {@code null}
 * @param strip if {@code true}, strip the {@code prefix} off of the property key in the returned {@code Map}
 * @return a {@code Map} containing the enumerated property keys and values from {@code sources}
 */
public static Map<String, Object> asMap(MutablePropertySources sources, String prefix, boolean strip) {
    Map<String, Object> props = new HashMap<>();

    filterEnumerablePropertySources(sources).forEach(source -> {
        if (!(source instanceof EnumerablePropertySource)) {
            return;
        }
        Stream.of(((EnumerablePropertySource)source).getPropertyNames())
                .filter(propName -> prefix == null || propName.startsWith(prefix))
                .peek(propName -> LOG.debug(
                        "Found kafka property prefix: [{}], property name: [{}]", prefix, propName))
                .collect(Collectors.toMap(
                        propName -> (prefix == null || !strip || !propName.startsWith(prefix)) ?
                                propName : propName.substring(prefix.length()),
                        source::getProperty,
                        (val1, val2) -> {
                            LOG.debug("Merging kafka property value [{}], [{}]: [{}] wins",
                                    val1, val2, val2);
                            return val2;
                        },
                        () -> props
                ))
                .forEach((key, value) -> LOG.debug("Kafka property: [{}]=[{}]",
                        key, (isNullValue(value)) ? "null" : value));
    });
    return props;
}
项目:rmap    文件:KafkaPropertyUtils.java   
/**
 * Filters the supplied {@code MutablePropertySources} for instances of {@code EnumerablePropertySource}, and
 * returns a new {@code MutablePropertySource} containing <em>only</em> {@code EnumerablePropertySource} sources.
 *
 * @param sources property sources that may contain instances of {@code EnumerablePropertySource}
 * @return property sources that contain <em>only</em> {@code EnumerablePropertySource}
 */
public static MutablePropertySources filterEnumerablePropertySources(MutablePropertySources sources) {
    MutablePropertySources enumerableSources = new MutablePropertySources();

    sources.forEach(source -> {
                if (source instanceof EnumerablePropertySource) {
                    enumerableSources.addLast(source);
                }
            });
    return enumerableSources;
}
项目:spring4-understanding    文件:ConfigurationClassParser.java   
private void addPropertySource(ResourcePropertySource propertySource) {
    String name = propertySource.getName();
    MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
    if (propertySources.contains(name) && this.propertySourceNames.contains(name)) {
        // We've already added a version, we need to extend it
        PropertySource<?> existing = propertySources.get(name);
        if (existing instanceof CompositePropertySource) {
            ((CompositePropertySource) existing).addFirstPropertySource(propertySource.withResourceName());
        }
        else {
            if (existing instanceof ResourcePropertySource) {
                existing = ((ResourcePropertySource) existing).withResourceName();
            }
            CompositePropertySource composite = new CompositePropertySource(name);
            composite.addPropertySource(propertySource.withResourceName());
            composite.addPropertySource(existing);
            propertySources.replace(name, composite);
        }
    }
    else {
        if (this.propertySourceNames.isEmpty()) {
            propertySources.addLast(propertySource);
        }
        else {
            String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
            propertySources.addBefore(firstProcessed, propertySource);
        }
    }
    this.propertySourceNames.add(name);
}
项目:spring4-understanding    文件:PropertySourcesPlaceholderConfigurer.java   
/**
 * {@inheritDoc}
 * <p>Processing occurs by replacing ${...} placeholders in bean definitions by resolving each
 * against this configurer's set of {@link PropertySources}, which includes:
 * <ul>
 * <li>all {@linkplain org.springframework.core.env.ConfigurableEnvironment#getPropertySources
 * environment property sources}, if an {@code Environment} {@linkplain #setEnvironment is present}
 * <li>{@linkplain #mergeProperties merged local properties}, if {@linkplain #setLocation any}
 * {@linkplain #setLocations have} {@linkplain #setProperties been}
 * {@linkplain #setPropertiesArray specified}
 * <li>any property sources set by calling {@link #setPropertySources}
 * </ul>
 * <p>If {@link #setPropertySources} is called, <strong>environment and local properties will be
 * ignored</strong>. This method is designed to give the user fine-grained control over property
 * sources, and once set, the configurer makes no assumptions about adding additional sources.
 */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    if (this.propertySources == null) {
        this.propertySources = new MutablePropertySources();
        if (this.environment != null) {
            this.propertySources.addLast(
                new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {
                    @Override
                    public String getProperty(String key) {
                        return this.source.getProperty(key);
                    }
                }
            );
        }
        try {
            PropertySource<?> localPropertySource =
                    new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties());
            if (this.localOverride) {
                this.propertySources.addFirst(localPropertySource);
            }
            else {
                this.propertySources.addLast(localPropertySource);
            }
        }
        catch (IOException ex) {
            throw new BeanInitializationException("Could not load properties", ex);
        }
    }

    processProperties(beanFactory, new PropertySourcesPropertyResolver(this.propertySources));
    this.appliedPropertySources = this.propertySources;
}
项目:spring4-understanding    文件:StandardServletEnvironmentTests.java   
@Test
public void propertySourceOrder() throws Exception {
    SimpleNamingContextBuilder.emptyActivatedContextBuilder();

    ConfigurableEnvironment env = new StandardServletEnvironment();
    MutablePropertySources sources = env.getPropertySources();

    assertThat(sources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), equalTo(0));
    assertThat(sources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)), equalTo(1));
    assertThat(sources.precedenceOf(PropertySource.named(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)), equalTo(2));
    assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)), equalTo(3));
    assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)), equalTo(4));
    assertThat(sources.size(), is(5));
}
项目:spring4-understanding    文件:TestPropertySourceUtilsTests.java   
/**
 * @since 4.1.5
 */
@Test
@SuppressWarnings("rawtypes")
public void addInlinedPropertiesToEnvironmentWithEmptyProperty() {
    ConfigurableEnvironment environment = new MockEnvironment();
    MutablePropertySources propertySources = environment.getPropertySources();
    propertySources.remove(MockPropertySource.MOCK_PROPERTIES_PROPERTY_SOURCE_NAME);
    assertEquals(0, propertySources.size());
    addInlinedPropertiesToEnvironment(environment, new String[] { "  " });
    assertEquals(1, propertySources.size());
    assertEquals(0, ((Map) propertySources.iterator().next().getSource()).size());
}
项目:my-spring-cache-redis    文件:PropertySourcesPlaceholderConfigurer.java   
/**
 * {@inheritDoc}
 * <p>Processing occurs by replacing ${...} placeholders in bean definitions by resolving each
 * against this configurer's set of {@link PropertySources}, which includes:
 * <ul>
 * <li>all {@linkplain org.springframework.core.env.ConfigurableEnvironment#getPropertySources
 * environment property sources}, if an {@code Environment} {@linkplain #setEnvironment is present}
 * <li>{@linkplain #mergeProperties merged local properties}, if {@linkplain #setLocation any}
 * {@linkplain #setLocations have} {@linkplain #setProperties been}
 * {@linkplain #setPropertiesArray specified}
 * <li>any property sources set by calling {@link #setPropertySources}
 * </ul>
 * <p>If {@link #setPropertySources} is called, <strong>environment and local properties will be
 * ignored</strong>. This method is designed to give the user fine-grained control over property
 * sources, and once set, the configurer makes no assumptions about adding additional sources.
 */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    if (this.propertySources == null) {
        this.propertySources = new MutablePropertySources();
        if (this.environment != null) {
            this.propertySources.addLast(
                new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {
                    @Override
                    public String getProperty(String key) {
                        return this.source.getProperty(key);
                    }
                }
            );
        }
        try {
            PropertySource<?> localPropertySource =
                new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties());
            if (this.localOverride) {
                this.propertySources.addFirst(localPropertySource);
            }
            else {
                this.propertySources.addLast(localPropertySource);
            }
        }
        catch (IOException ex) {
            throw new BeanInitializationException("Could not load properties", ex);
        }
    }

    processProperties(beanFactory, new PropertySourcesPropertyResolver(this.propertySources));
    this.appliedPropertySources = this.propertySources;
}
项目:spring-vault    文件:VaultPropertySourceRegistrar.java   
private void registerPropertySources(
        Collection<? extends PropertySource<?>> propertySources,
        MutablePropertySources mutablePropertySources) {

    for (PropertySource<?> vaultPropertySource : propertySources) {

        if (propertySources.contains(vaultPropertySource.getName())) {
            continue;
        }

        mutablePropertySources.addLast(vaultPropertySource);
    }
}
项目:jeesuite-libs    文件:EnvironmentHelper.java   
public static Map<String, Object> getAllProperties(String prefix){
    init();
    if(environment == null)return null;
    MutablePropertySources propertySources = ((ConfigurableEnvironment)environment).getPropertySources();

    Map<String, Object> properties = new LinkedHashMap<String, Object>();
    for (PropertySource<?> source : propertySources) {
        if(source.getName().startsWith("servlet") || source.getName().startsWith("system")){
            continue;
        }
        if (source instanceof EnumerablePropertySource) {
            for (String name : ((EnumerablePropertySource<?>) source) .getPropertyNames()) {
                boolean match = StringUtils.isEmpty(prefix);
                if(!match){
                    match = name.startsWith(prefix);
                }
                if(match){                      
                    Object value = source.getProperty(name);
                    if(value != null){
                        properties.put(name, value);
                    }
                }
            }
        }
    }
    return Collections.unmodifiableMap(properties);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:PropertySourcesLoader.java   
/**
 * Create a new {@link PropertySourceLoader} instance backed by the specified
 * {@link MutablePropertySources}.
 * @param propertySources the destination property sources
 */
public PropertySourcesLoader(MutablePropertySources propertySources) {
    Assert.notNull(propertySources, "PropertySources must not be null");
    this.propertySources = propertySources;
    this.loaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class,
            getClass().getClassLoader());
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:SpringApplicationJsonEnvironmentPostProcessor.java   
private void addJsonPropertySource(ConfigurableEnvironment environment,
        PropertySource<?> source) {
    MutablePropertySources sources = environment.getPropertySources();
    String name = findPropertySource(sources);
    if (sources.contains(name)) {
        sources.addBefore(name, source);
    }
    else {
        sources.addFirst(source);
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:SpringApplicationJsonEnvironmentPostProcessor.java   
private String findPropertySource(MutablePropertySources sources) {
    if (ClassUtils.isPresent(SERVLET_ENVIRONMENT_CLASS, null) && sources
            .contains(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)) {
        return StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME;

    }
    return StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:ConfigurationPropertiesBindingPostProcessor.java   
private PropertySources deducePropertySources() {
    PropertySourcesPlaceholderConfigurer configurer = getSinglePropertySourcesPlaceholderConfigurer();
    if (configurer != null) {
        // Flatten the sources into a single list so they can be iterated
        return new FlatPropertySources(configurer.getAppliedPropertySources());
    }
    if (this.environment instanceof ConfigurableEnvironment) {
        MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment)
                .getPropertySources();
        return new FlatPropertySources(propertySources);
    }
    // empty, so not very useful, but fulfils the contract
    return new MutablePropertySources();
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:ConfigurationPropertiesBindingPostProcessor.java   
private MutablePropertySources getFlattened() {
    MutablePropertySources result = new MutablePropertySources();
    for (PropertySource<?> propertySource : this.propertySources) {
        flattenPropertySources(propertySource, result);
    }
    return result;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:ConfigurationPropertiesBindingPostProcessor.java   
private void flattenPropertySources(PropertySource<?> propertySource,
        MutablePropertySources result) {
    Object source = propertySource.getSource();
    if (source instanceof ConfigurableEnvironment) {
        ConfigurableEnvironment environment = (ConfigurableEnvironment) source;
        for (PropertySource<?> childSource : environment.getPropertySources()) {
            flattenPropertySources(childSource, result);
        }
    }
    else {
        result.addLast(propertySource);
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:ConfigFileApplicationListener.java   
private void addConfigurationProperties(MutablePropertySources sources) {
    List<PropertySource<?>> reorderedSources = new ArrayList<PropertySource<?>>();
    for (PropertySource<?> item : sources) {
        reorderedSources.add(item);
    }
    addConfigurationProperties(
            new ConfigurationPropertySources(reorderedSources));
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:ConfigFileApplicationListener.java   
private void addConfigurationProperties(
        ConfigurationPropertySources configurationSources) {
    MutablePropertySources existingSources = this.environment
            .getPropertySources();
    if (existingSources.contains(DEFAULT_PROPERTIES)) {
        existingSources.addBefore(DEFAULT_PROPERTIES, configurationSources);
    }
    else {
        existingSources.addLast(configurationSources);
    }
}