类org.springframework.boot.env.PropertySourceLoader源码实例Demo

下面列出了怎么用org.springframework.boot.env.PropertySourceLoader的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: 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");
}
 
源代码2 项目: mPaaS   文件: ResourceLoadFactory.java
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    PropertySource<?> propSource = null;
    String propName = name;
    if (StringUtils.isEmpty(propName)) {
        propName = getNameForResource(resource.getResource());
    }
    if (resource.getResource().exists()) {
        String fileName = resource.getResource().getFilename();
        for (PropertySourceLoader loader : loaders) {
            if (checkFileType(fileName, loader.getFileExtensions())) {
                List<PropertySource<?>> propertySources = loader.load(propName, resource.getResource());
                if (!propertySources.isEmpty()) {
                    propSource = propertySources.get(0);
                }
            }
        }
    } else {
        throw new FileNotFoundException(propName + "对应文件'" + resource.getResource().getFilename() + "'不存在");
    }
    return propSource;
}
 
源代码3 项目: mPass   文件: ResourceLoadFactory.java
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    PropertySource<?> propSource = null;
    String propName = name;
    if (StringUtils.isEmpty(propName)) {
        propName = getNameForResource(resource.getResource());
    }
    if (resource.getResource().exists()) {
        String fileName = resource.getResource().getFilename();
        for (PropertySourceLoader loader : loaders) {
            if (checkFileType(fileName, loader.getFileExtensions())) {
                List<PropertySource<?>> propertySources = loader.load(propName, resource.getResource());
                if (!propertySources.isEmpty()) {
                    propSource = propertySources.get(0);
                }
            }
        }
    } else {
        throw new FileNotFoundException(propName + "对应文件'" + resource.getResource().getFilename() + "'不存在");
    }
    return propSource;
}
 
void load(String location, PropertySourceLoader loader) {
    try {
        Resource resource = resourceLoader.getResource(location);
        if (!resource.exists()) {
            return;
        }
        String propertyResourceName = "flowableDefaultConfig: [" + location + "]";

        List<PropertySource<?>> propertySources = loader.load(propertyResourceName, resource);
        if (propertySources == null) {
            return;
        }
        propertySources.forEach(source -> environment.getPropertySources().addLast(source));
    } catch (Exception ex) {
        throw new IllegalStateException("Failed to load property "
            + "source from location '" + location + "'", ex);
    }
}
 
private PropertySource createPropertySource(AnnotationAttributes attributes, ConfigurableEnvironment environment, ResourceLoader resourceLoader, EncryptablePropertyResolver resolver, EncryptablePropertyFilter propertyFilter, List<PropertySourceLoader> loaders) throws Exception {
    String name = generateName(attributes.getString("name"));
    String[] locations = attributes.getStringArray("value");
    boolean ignoreResourceNotFound = attributes.getBoolean("ignoreResourceNotFound");
    CompositePropertySource compositePropertySource = new CompositePropertySource(name);
    Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
    for (String location : locations) {
        String resolvedLocation = environment.resolveRequiredPlaceholders(location);
        Resource resource = resourceLoader.getResource(resolvedLocation);
        if (!resource.exists()) {
            if (!ignoreResourceNotFound) {
                throw new IllegalStateException(String.format("Encryptable Property Source '%s' from location: %s Not Found", name, resolvedLocation));
            } else {
                log.info("Ignoring NOT FOUND Encryptable Property Source '{}' from locations: {}", name, resolvedLocation);
            }
        } else {
            String actualName = name + "#" + resolvedLocation;
            loadPropertySource(loaders, resource, actualName)
                    .ifPresent(psources -> psources.forEach(compositePropertySource::addPropertySource));
        }
    }
    return new EncryptableEnumerablePropertySourceWrapper<>(compositePropertySource, resolver, propertyFilter);
}
 
源代码6 项目: Qualitis   文件: ConfigPrinter.java
private PropertySourceLoader getPropertySourceLoader(String fileName) throws UnSupportConfigFileSuffixException {
    if (fileName.contains(PROPERTIES_FILE_EXTENSION)) {
        return new PropertiesPropertySourceLoader();
    } else if (fileName.contains(YAML_FILE_EXTENSION)) {
        return new YamlPropertySourceLoader();
    }
    LOGGER.error("Failed to recognize file: {}", fileName);
    throw new UnSupportConfigFileSuffixException();
}
 
private static void loadPropertySource(String location, Resource resource,
									   PropertySourceLoader loader,
									   List<PropertySource> sourceList) {
	if (resource.exists()) {
		String name = "MagicPropertySource: [" + location + "]";
		try {
			sourceList.addAll(loader.load(name, resource));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
 
Loader(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
    this.environment = environment;
    this.resourceLoader = resourceLoader == null ? new DefaultResourceLoader()
        : resourceLoader;
    this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(
        PropertySourceLoader.class, getClass().getClassLoader());
}
 
void load() {
    for (PropertySourceLoader loader : propertySourceLoaders) {
        for (String extension : loader.getFileExtensions()) {
            String location = "classpath:/" + FlowableDefaultPropertiesEnvironmentPostProcessor.DEFAULT_NAME + "." + extension;
            load(location, loader);
        }
    }

}
 
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    ResourceLoader ac = new DefaultResourceLoader();
    MutablePropertySources propertySources = env.getPropertySources();
    Stream<AnnotationAttributes> encryptablePropertySourcesMetadata = getEncryptablePropertySourcesMetadata(beanFactory);
    EncryptablePropertyResolver propertyResolver = beanFactory.getBean(RESOLVER_BEAN_NAME, EncryptablePropertyResolver.class);
    EncryptablePropertyFilter propertyFilter = beanFactory.getBean(FILTER_BEAN_NAME, EncryptablePropertyFilter.class);
    List<PropertySourceLoader> loaders = initPropertyLoaders();
    encryptablePropertySourcesMetadata.forEach(eps -> loadEncryptablePropertySource(eps, env, ac, propertyResolver, propertyFilter, propertySources, loaders));
}
 
private void loadEncryptablePropertySource(AnnotationAttributes encryptablePropertySource, ConfigurableEnvironment env, ResourceLoader resourceLoader, EncryptablePropertyResolver resolver, EncryptablePropertyFilter propertyFilter, MutablePropertySources propertySources, List<PropertySourceLoader> loaders) throws BeansException {
    try {
        log.info("Loading Encryptable Property Source '{}'", encryptablePropertySource.getString("name"));
        PropertySource ps = createPropertySource(encryptablePropertySource, env, resourceLoader, resolver, propertyFilter, loaders);
        propertySources.addLast(ps);
        log.info("Created Encryptable Property Source '{}' from locations: {}", ps.getName(), Arrays.asList(encryptablePropertySource.getStringArray("value")));
    } catch (Exception e) {
        throw new ApplicationContextException("Exception Creating PropertySource", e);
    }
}
 
private Optional<List<PropertySource<?>>> loadPropertySource(List<PropertySourceLoader> loaders, Resource resource, String sourceName) throws IOException {
    return Optional.of(resource)
            .filter(this::isFile)
            .flatMap(res -> loaders.stream()
                    .filter(loader -> canLoadFileExtension(loader, resource))
                    .findFirst()
                    .map(loader -> load(loader, sourceName, resource)));
}
 
public MagicPropertySourcePostProcessor() {
	this.resourceLoader = new DefaultResourceLoader();
	this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, getClass().getClassLoader());
}
 
private List<PropertySourceLoader> initPropertyLoaders() {
    return SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, getClass().getClassLoader());
}
 
@SneakyThrows
private List<PropertySource<?>> load(PropertySourceLoader loader, String sourceName, Resource resource) {
    return loader.load(sourceName, resource);
}
 
private boolean canLoadFileExtension(PropertySourceLoader loader, Resource resource) {
    return Arrays.stream(loader.getFileExtensions())
            .anyMatch(extension -> Objects.requireNonNull(resource.getFilename()).toLowerCase().endsWith("." + extension.toLowerCase()));
}
 
public static void main(String[] args) {

        List<PropertySourceLoader> propertySourceLoaders = loadFactories(PropertySourceLoader.class, PropertySourceLoader.class.getClassLoader());

        propertySourceLoaders.forEach(System.out::println);

    }
 
 类所在包
 类方法
 同包方法