org.springframework.boot.context.properties.source.ConfigurationPropertySource Java Examples

The following examples show how to use org.springframework.boot.context.properties.source.ConfigurationPropertySource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BinderBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 7 votes vote down vote up
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();
}
 
Example #2
Source File: ExternalizedConfigurationBinderBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 7 votes vote down vote up
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);

}
 
Example #3
Source File: GenericPropertiesConfiguration.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #4
Source File: SpringConfigurationPropertySource.java    From synopsys-detect with Apache License 2.0 6 votes vote down vote up
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();

}
 
Example #5
Source File: ConfigurationPropertySourcesBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #6
Source File: BinderDubboConfigBinder.java    From dubbo-spring-boot-project with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: GenericPropertiesConfiguration.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #8
Source File: ConfigurationService.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #9
Source File: XADataSourceBuilder.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #10
Source File: ConfigureAgentStage.java    From genie with Apache License 2.0 5 votes vote down vote up
@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)
        );
}
 
Example #11
Source File: DataSourceSpiBuilder.java    From ByteJTA with GNU Lesser General Public License v3.0 5 votes vote down vote up
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));
}
 
Example #12
Source File: ServiceBrokerPropertiesTest.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #13
Source File: RiptidePostProcessor.java    From riptide with MIT License 5 votes vote down vote up
@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));
}
 
Example #14
Source File: SpringConfigurationPropertySource.java    From synopsys-detect with Apache License 2.0 5 votes vote down vote up
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."));
        }
    }
}
 
Example #15
Source File: DetectCustomFieldParser.java    From synopsys-detect with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #16
Source File: DataSourceFactory.java    From Milkomeda with MIT License 4 votes vote down vote up
@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));
}
 
Example #17
Source File: MangoConfigFactory.java    From mango-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
private static Iterable<ConfigurationPropertySource> getConfigurationPropertySources(PropertySources propertySources) {
    return ConfigurationPropertySources.from(propertySources);
}
 
Example #18
Source File: DataSourceCciBuilder.java    From ByteJTA with GNU Lesser General Public License v3.0 4 votes vote down vote up
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));
}
 
Example #19
Source File: CustomizedConfigurationPropertiesBinder.java    From apollo-use-cases with Apache License 2.0 4 votes vote down vote up
private Iterable<ConfigurationPropertySource> getConfigurationPropertySources() {
  return ConfigurationPropertySources.from(this.propertySources);
}
 
Example #20
Source File: InitializrMetadataBuilderTests.java    From initializr with Apache License 2.0 4 votes vote down vote up
private static InitializrProperties load(Resource resource) {
	ConfigurationPropertySource source = new MapConfigurationPropertySource(loadProperties(resource));
	Binder binder = new Binder(source);
	return binder.bind("initializr", InitializrProperties.class).get();
}