org.springframework.core.env.PropertySource#getSource ( )源码实例Demo

下面列出了org.springframework.core.env.PropertySource#getSource ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@PostConstruct
public void init() {
    jexlEngine = new JexlBuilder().create();
    // 支持的参数
    // 1. 启动参数
    // 2. 测试配置变量
    // 3. 系统属性
    PropertySource<?> ps = environment.getPropertySources().get("systemProperties");
    Map<Object, Object> source = (Map<Object, Object>) ps.getSource();
    source.forEach((key, value) -> {
        if (!jc.has(keyed((String) key))) {
            jc.set(keyed((String) key), value);
        }
    });

    // 4. 环境变量
    ps = environment.getPropertySources().get("systemEnvironment");
    source = (Map<Object, Object>) ps.getSource();
    source.forEach((key, value) -> {
        if (!jc.has(keyed((String) key))) {
            jc.set(keyed((String) key), value);
        }
    });
}
 
源代码2 项目: Qualitis   文件: ConfigPrinter.java
@PostConstruct
public void printConfig() throws UnSupportConfigFileSuffixException {
    LOGGER.info("Start to print config");
    addPropertiesFile();
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    LOGGER.info("Prepared to print config in file: {}", propertiesFiles);

    for (String fileName : propertiesFiles) {
        LOGGER.info("======================== Config in {} ========================", fileName);
        PropertySourceLoader propertySourceLoader = getPropertySourceLoader(fileName);
        Resource resource = resourceLoader.getResource(fileName);
        try {
            List<PropertySource<?>> propertySources = propertySourceLoader.load(fileName, resource);
            for (PropertySource p : propertySources) {
                Map<String, Object> map = (Map<String, Object>) p.getSource();
                for (String key : map.keySet()) {
                    LOGGER.info("Name: [{}]=[{}]", key, map.get(key));
                }
            }
        } catch (IOException e) {
            LOGGER.info("Failed to open file: {}, caused by: {}, it does not matter", fileName, e.getMessage());
        }
        LOGGER.info("=======================================================================================\n");
    }
    LOGGER.info("Succeed to print all configs");
}
 
private ConfigurationPropertySource fetchNext() {
    if (this.next == null) {
        if (this.iterators.isEmpty()) {
            return null;
        }
        if (!this.iterators.peek().hasNext()) {
            this.iterators.pop();
            return fetchNext();
        }
        PropertySource<?> candidate = this.iterators.peek().next();
        if (candidate.getSource() instanceof ConfigurableEnvironment) {
            push((ConfigurableEnvironment) candidate.getSource());
            return fetchNext();
        }
        if (isIgnored(candidate)) {
            return fetchNext();
        }
        this.next = this.adapter.apply(candidate);
    }
    return this.next;
}
 
/**
 * Attach a {@link ConfigurationPropertySource} support to the specified
 * {@link Environment}. Adapts each {@link PropertySource} managed by the environment
 * to a {@link ConfigurationPropertySource} and allows classic
 * {@link PropertySourcesPropertyResolver} calls to resolve using
 * {@link ConfigurationPropertyName configuration property names}.
 * <p>
 * The attached resolver will dynamically track any additions or removals from the
 * underlying {@link Environment} property sources.
 *
 * @param environment the source environment (must be an instance of
 *                    {@link ConfigurableEnvironment})
 * @see #get(Environment)
 */
public static void attach(Environment environment) {
    Assert.isInstanceOf(ConfigurableEnvironment.class, environment);
    MutablePropertySources sources = ((ConfigurableEnvironment) environment)
            .getPropertySources();
    PropertySource<?> attached = sources.get(ATTACHED_PROPERTY_SOURCE_NAME);
    if (attached != null && attached.getSource() != sources) {
        sources.remove(ATTACHED_PROPERTY_SOURCE_NAME);
        attached = null;
    }
    if (attached == null) {
        sources.addFirst(new ConfigurationPropertySourcesPropertySource(
                ATTACHED_PROPERTY_SOURCE_NAME,
                new SpringConfigurationPropertySources(sources)));
    }
}
 
源代码5 项目: hasor   文件: AbstractEnvironmentAware.java
public Properties setupEnvironment(Environment environment) {
    this.environment = environment;
    Properties envProperties = new Properties();
    Iterator<PropertySource<?>> propertySourceIterator = ((StandardEnvironment) environment).getPropertySources().iterator();
    while (propertySourceIterator.hasNext()) {
        PropertySource<?> propertySource = propertySourceIterator.next();
        if ("systemProperties".equalsIgnoreCase(propertySource.getName())) {
            continue;// this propertySource in Hasor has same one
        }
        if ("systemEnvironment".equalsIgnoreCase(propertySource.getName())) {
            continue;// this propertySource in Hasor has same one
        }
        Object source = propertySource.getSource();
        if (source instanceof Map) {
            envProperties.putAll(((Map) source));
        }
    }
    return envProperties;
}
 
private static boolean isFullEnumerable(PropertySource<?> source) {
    PropertySource<?> rootSource = getRootSource(source);
    if (rootSource.getSource() instanceof Map) {
        // Check we're not security restricted
        try {
            ((Map<?, ?>) rootSource.getSource()).size();
        } catch (UnsupportedOperationException ex) {
            return false;
        }
    }
    return (source instanceof EnumerablePropertySource);
}
 
private static PropertySource<?> getRootSource(PropertySource<?> source) {
    while (source.getSource() != null
            && source.getSource() instanceof PropertySource) {
        source = (PropertySource<?>) source.getSource();
    }
    return source;
}
 
private static Function<ConfigurationPropertyName, ConfigurationPropertyState> getContainsDescendantOfForSource(
        PropertySource<?> source) {
    if (source.getSource() instanceof Random) {
        return SpringConfigurationPropertySource::containsDescendantOfForRandom;
    }
    return null;
}
 
private static Stream<PropertySource<?>> flatten(PropertySource<?> source) {
    if (source.getSource() instanceof ConfigurableEnvironment) {
        return streamPropertySources(
                ((ConfigurableEnvironment) source.getSource()).getPropertySources());
    }
    return Stream.of(source);
}
 
public CachingDelegateEncryptablePropertySource(PropertySource<T> delegate, EncryptablePropertyResolver resolver, EncryptablePropertyFilter filter) {
    super(delegate.getName(), delegate.getSource());
    Assert.notNull(delegate, "PropertySource delegate cannot be null");
    Assert.notNull(resolver, "EncryptablePropertyResolver cannot be null");
    Assert.notNull(filter, "EncryptablePropertyFilter cannot be null");
    this.delegate = delegate;
    this.resolver = resolver;
    this.filter = filter;
    this.cache = new HashMap<>();
}
 
@SuppressWarnings("unchecked")
private static Map<String, Object> findMap(PropertySource<?> propertySource) {
	if (propertySource instanceof MapPropertySource) {
		return (Map<String, Object>) propertySource.getSource();
	}
	return new LinkedHashMap<String, Object>();
}
 
private Map<String, Object> findTestProperties() {
	for (PropertySource<?> source : this.environment.getPropertySources()) {
		if (source.getName().toLowerCase().contains("test")) {
			@SuppressWarnings("unchecked")
			Map<String, Object> map = (Map<String, Object>) source.getSource();
			return map;
		}
	}
	throw new IllegalStateException("Could not find test property source");
}
 
private Map<String, Object> findTestProperties() {
	for (PropertySource<?> source : this.environment.getPropertySources()) {
		if (source.getName().toLowerCase().contains("test")) {
			@SuppressWarnings("unchecked")
			Map<String, Object> map = (Map<String, Object>) source.getSource();
			return map;
		}
	}
	throw new IllegalStateException("Could not find test property source");
}
 
public EncryptablePropertySourceWrapper(PropertySource<T> delegate, EncryptablePropertyResolver resolver, EncryptablePropertyFilter filter) {
    super(delegate.getName(), delegate.getSource());
    encryptableDelegate = new CachingDelegateEncryptablePropertySource<>(delegate, resolver, filter);
}
 
public SimpleBootstrapPropertySource(PropertySource<T> delegate) {
	super(BOOTSTRAP_PROPERTY_SOURCE_NAME + "-" + delegate.getName(),
			delegate.getSource());
	this.delegate = delegate;
}