类org.springframework.boot.context.properties.source.ConfigurationPropertySource源码实例Demo

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

public static List<SpringConfigurationPropertySource> fromConfigurableEnvironment(ConfigurableEnvironment configurableEnvironment, boolean ignoreUnknown) {
    List<ConfigurationPropertySource> sources = Bds.listOf(ConfigurationPropertySources.get(configurableEnvironment));
    return Bds.of(sources).map(it -> {
        if (IterableConfigurationPropertySource.class.isAssignableFrom(it.getClass())) {
            return getPropertySource(configurableEnvironment, ignoreUnknown, it);
        } else if (RandomValuePropertySource.class.isAssignableFrom(it.getUnderlyingSource().getClass())) {
            //We know an underlying random source can't be iterated but we don't care. It can't give a list of known keys.
            return null;
        } else {
            if (ignoreUnknown) {
                return null;
            } else {
                throw new RuntimeException(
                    new UnknownSpringConfigurationException("Unknown spring configuration type. We may be unable to find property information from it correctly. Likely a new configuration property source should be tested against. "));
            }
        }
    }).filterNotNull().toList();

}
 
public static void main(String[] args) {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(BinderBootstrap.class)
            .web(WebApplicationType.NONE) // 非 Web 应用
            .properties("user.city.postCode=0731")
            .run(args);
    ConfigurableEnvironment environment = context.getEnvironment();
    // 从 Environment 中获取 ConfigurationPropertySource 集合
    Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment);
    // 构造 Binder 对象,并使用 ConfigurationPropertySource 集合作为配置源
    Binder binder = new Binder(sources);
    // 构造 ConfigurationPropertyName(Spring Boot 2.0 API)
    ConfigurationPropertyName propertyName = ConfigurationPropertyName.of("user.city.post-code");
    // 构造 Bindable 对象,包装 postCode
    Bindable<String> postCodeBindable = Bindable.of(String.class);
    BindResult<String> result = binder.bind(propertyName, postCodeBindable);
    String postCode = result.get();
    System.out.println("postCode = " + postCode);
    // 关闭上下文
    context.close();
}
 
public static void main(String[] args) throws IOException {
    // application.properties 文件资源 classpath 路径
    String location = "application.properties";
    // 编码化的 Resource 对象(解决乱码问题)
    EncodedResource resource = new EncodedResource(new ClassPathResource(location), "UTF-8");
    // 加载 application.properties 文件,转化为 Properties 对象
    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
    // 创建 Properties 类型的 PropertySource
    PropertiesPropertySource propertySource = new PropertiesPropertySource("map", properties);
    // 转化为 Spring Boot 2 外部化配置源 ConfigurationPropertySource 集合
    Iterable<ConfigurationPropertySource> propertySources = ConfigurationPropertySources.from(propertySource);
    // 创建 Spring Boot 2 Binder 对象(设置 ConversionService ,扩展类型转换能力)
    Binder binder = new Binder(propertySources, null, conversionService());
    // 执行绑定,返回绑定结果
    BindResult<User> bindResult = binder.bind("user", User.class);
    // 获取绑定对象
    User user = bindResult.get();
    // 输出结果
    System.out.println(user);

}
 
public static void main(String[] args) {
    ConfigurableApplicationContext context =
            new SpringApplicationBuilder(
                    ConfigurationPropertySourcesBootstrap.class)
                    .properties("user.city.postCode=0571")
                    .web(WebApplicationType.NONE) // 非 Web 应用
                    .run(args);
    ConfigurableEnvironment environment = context.getEnvironment();
    // 从 Environment 中获取 ConfigurationPropertySource 集合
    Iterable<ConfigurationPropertySource> configurationPropertySources = ConfigurationPropertySources.get(environment);
    // 构造 ConfigurationPropertyName(Spring Boot 2.0 API)
    ConfigurationPropertyName propertyName = ConfigurationPropertyName.of("user.city.post-code");
    // 迭代 ConfigurationPropertySource
    configurationPropertySources.forEach(configurationPropertySource -> {
        // 通过 ConfigurationPropertyName 获取 ConfigurationProperty
        ConfigurationProperty configurationProperty = configurationPropertySource.getConfigurationProperty(propertyName);
        if (configurationProperty != null) {
            String postCode = (String) configurationProperty.getValue();
            System.out.println("postCode = " + postCode + " , from : " + configurationProperty.getOrigin());
        }
    });
    // 关闭上下文
    context.close();
}
 
@Override
public void bind(Map<String, Object> configurationProperties, boolean ignoreUnknownFields,
                 boolean ignoreInvalidFields, Object configurationBean) {

    Iterable<PropertySource<?>> propertySources = asList(new MapPropertySource("internal", configurationProperties));

    // Converts ConfigurationPropertySources
    Iterable<ConfigurationPropertySource> configurationPropertySources = from(propertySources);

    // Wrap Bindable from DubboConfig instance
    Bindable bindable = Bindable.ofInstance(configurationBean);

    Binder binder = new Binder(configurationPropertySources, new PropertySourcesPlaceholdersResolver(propertySources));

    // Get BindHandler
    BindHandler bindHandler = getBindHandler(ignoreUnknownFields, ignoreInvalidFields);

    // Bind
    binder.bind("", bindable, bindHandler);
}
 
static <T> T bindOrCreate(Bindable<T> bindable,
		Map<String, Object> properties, String configurationPropertyName,
		Validator validator, ConversionService conversionService) {
	// see ConfigurationPropertiesBinder from spring boot for this definition.
	BindHandler handler = new IgnoreTopLevelConverterNotFoundBindHandler();

	if (validator != null) { // TODO: list of validators?
		handler = new ValidationBindHandler(handler, validator);
	}

	List<ConfigurationPropertySource> propertySources = Collections
			.singletonList(new MapConfigurationPropertySource(properties));

	return new Binder(propertySources, null, conversionService)
			.bindOrCreate(configurationPropertyName, bindable, handler);
}
 
@Override
public void preInit(SpringProcessEngineConfiguration springProcessEngineConfiguration) {
  GenericProperties genericProperties = camundaBpmProperties.getGenericProperties();
  final Map<String, Object> properties = genericProperties.getProperties();

  if (!CollectionUtils.isEmpty(properties)) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
    Binder binder = new Binder(source);
    try {
      if (genericProperties.isIgnoreUnknownFields()) {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration));
      } else {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration), new NoUnboundElementsBindHandler(BindHandler.DEFAULT));
      }
    } catch (Exception e) {
      throw LOG.exceptionDuringBinding(e.getMessage());
    }
    logger.debug("properties bound to configuration: {}", genericProperties);
  }
}
 
@Override
public void preInit(SpringProcessEngineConfiguration springProcessEngineConfiguration) {
  GenericProperties genericProperties = camundaBpmProperties.getGenericProperties();
  final Map<String, Object> properties = genericProperties.getProperties();

  if (!CollectionUtils.isEmpty(properties)) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
    Binder binder = new Binder(source);
    try {
      if (genericProperties.isIgnoreUnknownFields()) {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration));
      } else {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration), new NoUnboundElementsBindHandler(BindHandler.DEFAULT));
      }
    } catch (Exception e) {
      throw LOG.exceptionDuringBinding(e.getMessage());
    }
    logger.debug("properties bound to configuration: {}", genericProperties);
  }
}
 
源代码9 项目: synopsys-detect   文件: DetectCustomFieldParser.java
public CustomFieldDocument parseCustomFieldDocument(final Map<String, String> currentProperties) throws DetectUserFriendlyException {
    try {
        final ConfigurationPropertySource source = new MapConfigurationPropertySource(currentProperties);
        final Binder objectBinder = new Binder(source);
        final BindResult<CustomFieldDocument> fieldDocumentBinding = objectBinder.bind("detect.custom.fields", CustomFieldDocument.class);
        final CustomFieldDocument fieldDocument = fieldDocumentBinding.orElse(new CustomFieldDocument());
        fieldDocument.getProject().forEach(this::filterEmptyQuotes);
        fieldDocument.getVersion().forEach(this::filterEmptyQuotes);
        return fieldDocument;
    } catch (final Exception e) {
        throw new DetectUserFriendlyException("Unable to parse custom fields.", e, ExitCodeType.FAILURE_CONFIGURATION);
    }
}
 
private static SpringConfigurationPropertySource getPropertySource(ConfigurableEnvironment configurableEnvironment, boolean ignoreUnknown, ConfigurationPropertySource configurationPropertySource) {
    Object underlying = configurationPropertySource.getUnderlyingSource();
    if (org.springframework.core.env.PropertySource.class.isAssignableFrom(underlying.getClass())) {
        org.springframework.core.env.PropertySource springSource = (org.springframework.core.env.PropertySource) underlying;
        return new SpringConfigurationPropertySource(springSource.getName(), (IterableConfigurationPropertySource) configurationPropertySource, configurableEnvironment);
    } else {
        if (ignoreUnknown) {
            return null;
        } else {
            throw new RuntimeException(
                new UnknownSpringConfigurationException("Unknown underlying spring configuration source. We may be unable to determine where a property originated. Likely a new property source type should be tested against."));
        }
    }
}
 
源代码11 项目: teiid-spring-boot   文件: XADataSourceBuilder.java
private void bindXaProperties(Bindable<XADataSource> target) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(
            this.properties);
    ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
    aliases.addAliases("url", "jdbc-url");
    aliases.addAliases("username", "user");
    aliases.addAliases("portNumber", "port");
    aliases.addAliases("serverName", "server");
    aliases.addAliases("databaseName", "database");

    Binder binder = new Binder(source.withAliases(aliases));
    binder.bind(ConfigurationPropertyName.EMPTY, target);
}
 
源代码12 项目: riptide   文件: RiptidePostProcessor.java
@Override
public void setEnvironment(final Environment environment) {
    final Iterable<ConfigurationPropertySource> sources =
            from(((ConfigurableEnvironment) environment).getPropertySources());
    final Binder binder = new Binder(sources,
            new PropertySourcesPlaceholdersResolver(environment));

    this.properties = Defaulting.withDefaults(binder.bindOrCreate("riptide", RiptideProperties.class));
}
 
private ServiceBrokerProperties bindProperties() {
	ConfigurationPropertySource source = new MapConfigurationPropertySource(this.map);
	Binder binder = new Binder(source);
	ServiceBrokerProperties serviceBrokerProperties = new ServiceBrokerProperties();
	binder.bind(PREFIX, Bindable.ofInstance(serviceBrokerProperties));
	return serviceBrokerProperties;
}
 
源代码14 项目: ByteJTA   文件: DataSourceSpiBuilder.java
private void bind(XADataSource result) {
	ConfigurationPropertySource source = new MapConfigurationPropertySource(this.properties);
	ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
	aliases.addAliases("url", "jdbc-url");
	aliases.addAliases("username", "user");
	Binder binder = new Binder(source.withAliases(aliases));
	binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result));
}
 
源代码15 项目: genie   文件: ConfigureAgentStage.java
@Override
protected void attemptStageAction(
    final ExecutionContext executionContext
) throws RetryableJobExecutionException, FatalJobExecutionException {

    final AgentClientMetadata agentClientMetadata = executionContext.getAgentClientMetadata();
    final AgentProperties agentProperties = executionContext.getAgentProperties();

    // Obtain server-provided properties
    final Map<String, String> serverPropertiesMap;
    try {
        serverPropertiesMap = this.agentJobService.configure(agentClientMetadata);
    } catch (ConfigureException e) {
        throw new RetryableJobExecutionException("Failed to obtain configuration", e);
    }

    for (final Map.Entry<String, String> entry : serverPropertiesMap.entrySet()) {
        log.info("Received property {}={}", entry.getKey(), entry.getValue());
    }

    // Bind properties received
    final ConfigurationPropertySource serverPropertiesSource =
        new MapConfigurationPropertySource(serverPropertiesMap);

    new Binder(serverPropertiesSource)
        .bind(
            AgentProperties.PREFIX,
            Bindable.ofInstance(agentProperties)
        );
}
 
源代码16 项目: Milkomeda   文件: DataSourceFactory.java
@SuppressWarnings("rawtypes")
private void bind(DataSource result, Map properties) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
    Binder binder = new Binder(source.withAliases(ALIASES));
    binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result));
}
 
private Iterable<ConfigurationPropertySource> getConfigurationPropertySources() {
  return ConfigurationPropertySources.from(this.propertySources);
}
 
private static Iterable<ConfigurationPropertySource> getConfigurationPropertySources(PropertySources propertySources) {
    return ConfigurationPropertySources.from(propertySources);
}
 
源代码19 项目: ByteJTA   文件: DataSourceCciBuilder.java
private void bind(DataSource dataSource) {
	ConfigurationPropertySource source = new MapConfigurationPropertySource(this.properties);
	ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
	Binder binder = new Binder(source.withAliases(aliases));
	binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(dataSource));
}
 
private static InitializrProperties load(Resource resource) {
	ConfigurationPropertySource source = new MapConfigurationPropertySource(loadProperties(resource));
	Binder binder = new Binder(source);
	return binder.bind("initializr", InitializrProperties.class).get();
}
 
 类所在包
 类方法
 同包方法