org.springframework.boot.context.properties.bind.BindResult Java Examples

The following examples show how to use org.springframework.boot.context.properties.bind.BindResult. 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: SpringdocBeanFactoryConfigurer.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)  {
	final BindResult<SpringDocConfigProperties> result = Binder.get(environment)
			.bind(SPRINGDOC_PREFIX, SpringDocConfigProperties.class);
	if (result.isBound()) {
		SpringDocConfigProperties springDocGroupConfig = result.get();
		List<GroupedOpenApi> groupedOpenApis = springDocGroupConfig.getGroupConfigs().stream()
				.map(elt -> {
					GroupedOpenApi.Builder builder = GroupedOpenApi.builder();
					if (!CollectionUtils.isEmpty(elt.getPackagesToScan()))
						builder.packagesToScan(elt.getPackagesToScan().toArray(new String[0]));
					if (!CollectionUtils.isEmpty(elt.getPathsToMatch()))
						builder.pathsToMatch(elt.getPathsToMatch().toArray(new String[0]));
					return builder.group(elt.getGroup()).build();
				})
				.collect(Collectors.toList());
		groupedOpenApis.forEach(elt -> beanFactory.registerSingleton(elt.getGroup(), elt));
	}
	initBeanFactoryPostProcessor(beanFactory);
}
 
Example #4
Source File: OSSCondition.java    From jeecg-boot-with-activiti with MIT License 6 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
	String sourceClass = "";
	if (metadata instanceof ClassMetadata) {
		sourceClass = ((ClassMetadata) metadata).getClassName();
	}
	ConditionMessage.Builder message = ConditionMessage.forCondition("OSS", sourceClass);
	Environment environment = context.getEnvironment();
	try {
		BindResult<OSSType> specified = Binder.get(environment).bind("oss.type", OSSType.class);
		if (!specified.isBound()) {
			return ConditionOutcome.match(message.because("automatic OSS type"));
		}
		OSSType required = OSSConfigurations.getType(((AnnotationMetadata) metadata).getClassName());
		if (specified.get() == required) {
			return ConditionOutcome.match(message.because(specified.get() + " OSS type"));
		}
	}
	catch (BindException ex) {
	}
	return ConditionOutcome.noMatch(message.because("unknown OSS type"));
}
 
Example #5
Source File: EncodingDecodingBindAdviceHandler.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
@Override
public BindHandler apply(BindHandler bindHandler) {
	BindHandler handler = new AbstractBindHandler(bindHandler) {
		@Override
		public <T> Bindable<T> onStart(ConfigurationPropertyName name,
									Bindable<T> target, BindContext context) {
			final String configName = name.toString();
			if (configName.contains("use") && configName.contains("native") &&
					(configName.contains("encoding") || configName.contains("decoding"))) {
				BindResult<T> result = context.getBinder().bind(name, target);
				if (result.isBound()) {
					if (configName.contains("encoding")) {
						EncodingDecodingBindAdviceHandler.this.encodingSettingProvided = true;
					}
					else {
						EncodingDecodingBindAdviceHandler.this.decodingSettingProvided = true;
					}
					return target.withExistingValue(result.get());
				}
			}
			return bindHandler.onStart(name, target, context);
		}
	};
	return handler;
}
 
Example #6
Source File: BindingHandlerAdvise.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Override
public BindHandler apply(BindHandler bindHandler) {


	BindHandler handler = new AbstractBindHandler(bindHandler) {
		@Override
		public <T> Bindable<T> onStart(ConfigurationPropertyName name,
				Bindable<T> target, BindContext context) {
			ConfigurationPropertyName defaultName = getDefaultName(name);
			if (defaultName != null) {
				BindResult<T> result = context.getBinder().bind(defaultName, target);
				if (result.isBound()) {
					return target.withExistingValue(result.get());
				}
			}
			return bindHandler.onStart(name, target, context);
		}
	};
	return handler;
}
 
Example #7
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 #8
Source File: MangoConfigFactory.java    From mango-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 获取配置
 *
 * @param beanFactory beanFactory
 * @param prefix 前缀
 * @return
 */
public static MangoConfig getMangoConfig(DefaultListableBeanFactory beanFactory, String prefix) {
    MangoConfig config = new MangoConfig();
    Bindable<?> target = Bindable.ofInstance(config);
    PropertySources propertySources = getPropertySources(beanFactory);
    BindHandler bindHandler = getBindHandler();
    BindResult configBindResult = getBinder(propertySources, beanFactory).bind(prefix, target, bindHandler);
    return (MangoConfig) configBindResult.get();
}
 
Example #9
Source File: KafkaStreamsBinderSupportAutoConfiguration.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "spring.cloud.stream.kafka.streams.binder")
public KafkaStreamsBinderConfigurationProperties binderConfigurationProperties(
		KafkaProperties kafkaProperties, ConfigurableEnvironment environment,
		BindingServiceProperties properties, ConfigurableApplicationContext context) throws Exception {
	final Map<String, BinderConfiguration> binderConfigurations = getBinderConfigurations(
			properties);
	for (Map.Entry<String, BinderConfiguration> entry : binderConfigurations
			.entrySet()) {
		final BinderConfiguration binderConfiguration = entry.getValue();
		final String binderType = binderConfiguration.getBinderType();
		if (binderType != null && (binderType.equals(KSTREAM_BINDER_TYPE)
				|| binderType.equals(KTABLE_BINDER_TYPE)
				|| binderType.equals(GLOBALKTABLE_BINDER_TYPE))) {
			Map<String, Object> binderProperties = new HashMap<>();
			this.flatten(null, binderConfiguration.getProperties(), binderProperties);
			environment.getPropertySources().addFirst(
					new MapPropertySource(entry.getKey() + "-kafkaStreamsBinderEnv", binderProperties));

			Binder binder = new Binder(ConfigurationPropertySources.get(environment),
					new PropertySourcesPlaceholdersResolver(environment),
					IntegrationUtils.getConversionService(context.getBeanFactory()), null);
			final Constructor<KafkaStreamsBinderConfigurationProperties> kafkaStreamsBinderConfigurationPropertiesConstructor =
					ReflectionUtils.accessibleConstructor(KafkaStreamsBinderConfigurationProperties.class, KafkaProperties.class);
			final KafkaStreamsBinderConfigurationProperties kafkaStreamsBinderConfigurationProperties =
					BeanUtils.instantiateClass(kafkaStreamsBinderConfigurationPropertiesConstructor, kafkaProperties);
			final BindResult<KafkaStreamsBinderConfigurationProperties> bind = binder.bind("spring.cloud.stream.kafka.streams.binder", Bindable.ofInstance(kafkaStreamsBinderConfigurationProperties));
			context.getBeanFactory().registerSingleton(
					entry.getKey() + "-KafkaStreamsBinderConfigurationProperties",
					bind.get());
		}
	}
	return new KafkaStreamsBinderConfigurationProperties(kafkaProperties);
}
 
Example #10
Source File: ApplicationMetricsProperties.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
private Map<String, String> bindProperties() {
	Map<String, String> target;
	BindResult<Map<String, String>> bindResult = Binder.get(this.environment).bind("",
			STRING_STRING_MAP);
	if (bindResult.isBound()) {
		target = bindResult.get();
	}
	else {
		target = new HashMap<>();
	}
	return target;
}
 
Example #11
Source File: FunctionalConfigurationPropertiesBinder.java    From spring-fu with Apache License 2.0 4 votes vote down vote up
public <T> BindResult<T> bind(String prefix, Bindable<T> target) {
	UnboundElementsSourceFilter filter = new UnboundElementsSourceFilter();
	NoUnboundElementsBindHandler handler = new NoUnboundElementsBindHandler(new IgnoreTopLevelConverterNotFoundBindHandler(), filter);
	return binder.bind(prefix, target, handler);
}