下面列出了怎么用org.springframework.boot.context.properties.bind.BindResult的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@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"));
}
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);
}
@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;
}
@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;
}
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);
}
}
/**
* 获取配置
*
* @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();
}
@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);
}
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;
}
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);
}