/** * Bind the environment to the {@link SpringApplication}. * @param environment the environment to bind */ protected void bindToSpringApplication(ConfigurableEnvironment environment) { try { Binder.get(environment).bind("spring.main", Bindable.ofInstance(this)); } catch (Exception ex) { throw new IllegalStateException("Cannot bind to SpringApplication", ex); } }
private void bind(Object bean, String beanName, ConfigurationProperties annotation) { ResolvableType type = getBeanType(bean, beanName); Validated validated = getAnnotation(bean, beanName, Validated.class); Annotation[] annotations = (validated != null) ? new Annotation[] { annotation, validated } : new Annotation[] { annotation }; Bindable<?> target = Bindable.of(type).withExistingValue(bean) .withAnnotations(annotations); try { this.configurationPropertiesBinder.bind(target); } catch (Exception ex) { throw new ConfigurationPropertiesBindException(beanName, bean, annotation, ex); } }
/** * Create a new {@link Bindable} of the type of the specified instance with an * existing value equal to the instance. * @param <T> the source type * @param instance the instance (must not be {@code null}) * @return a {@link Bindable} instance * @see #of(ResolvableType) * @see #withExistingValue(Object) */ @SuppressWarnings("unchecked") public static <T> Bindable<T> ofInstance(T instance) { Assert.notNull(instance, "Instance must not be null"); Class<T> type = (Class<T>) instance.getClass(); return of(type).withExistingValue(instance); }
private <T> boolean bind(BeanSupplier<T> beanSupplier, BeanPropertyBinder propertyBinder, BeanProperty property) { String propertyName = property.getName(); ResolvableType type = property.getType(); Supplier<Object> value = property.getValue(beanSupplier); Annotation[] annotations = property.getAnnotations(); Object bound = propertyBinder.bindProperty(propertyName, Bindable.of(type).withSuppliedValue(value).withAnnotations(annotations)); if (bound == null) { return false; } if (property.isSettable()) { property.setValue(beanSupplier, bound); } else if (value == null || !bound.equals(value.get())) { throw new IllegalStateException( "No setter found for property: " + property.getName()); } return true; }
/** * Create a new {@link Bindable} {@link Map} of the specified key and value type. * @param <K> the key type * @param <V> the value type * @param keyType the map key type * @param valueType the map value type * @return a {@link Bindable} instance */ public static <K, V> Bindable<Map<K, V>> mapOf(Class<K> keyType, Class<V> valueType) { return of(ResolvableType.forClassWithGenerics(Map.class, keyType, valueType)); }
public static Map<String, String> getSubProperties(Environment environment, String keyPrefix) { return Binder.get(environment) .bind(keyPrefix, Bindable.mapOf(String.class, String.class)) .orElseGet(Collections::emptyMap); } }
protected void setLogLevels(LoggingSystem system, Environment environment) { if (!(environment instanceof ConfigurableEnvironment)) { return; } Binder binder = Binder.get(environment); Map<String, String[]> groups = getGroups(); binder.bind(LOGGING_GROUP, STRING_STRINGS_MAP.withExistingValue(groups)); Map<String, String> levels = binder.bind(LOGGING_LEVEL, STRING_STRING_MAP) .orElseGet(Collections::emptyMap); levels.forEach((name, level) -> { String[] groupedNames = groups.get(name); if (ObjectUtils.isEmpty(groupedNames)) { setLogLevel(system, name, level); } else { setLogLevel(system, groupedNames, level); } }); }
private Set<String> bind(Binder binder, String name) { return asSet(binder.bind(name, Bindable.listOf(String.class)).map(this::cleanup) .orElseGet(ArrayList::new)); }
/** * Create a new {@link Bindable} of the specified type. * @param <T> the source type * @param type the type (must not be {@code null}) * @return a {@link Bindable} instance * @see #of(ResolvableType) */ public static <T> Bindable<T> of(Class<T> type) { Assert.notNull(type, "Type must not be null"); return of(ResolvableType.forClass(type)); }
/** * create a hikari data source * @see org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.Hikari#dataSource */ public HikariDataSource createDataSource() { HikariDataSource dataSource = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build(); if (StringUtils.hasText(dataSourceProperties.getName())) { dataSource.setPoolName(dataSourceProperties.getName()); } Bindable<?> target = Bindable.of(HikariDataSource.class).withExistingValue(dataSource); this.binder.bind("spring.datasource.hikari", target); return dataSource; }
private void reinitializeLoggingSystem(ConfigurableEnvironment environment, String oldLogConfig, LogFile oldLogFile) { Map<String, Object> props = Binder.get(environment) .bind("logging", Bindable.mapOf(String.class, Object.class)).orElseGet(Collections::emptyMap); if (!props.isEmpty()) { String logConfig = environment.resolvePlaceholders("${logging.config:}"); LogFile logFile = LogFile.get(environment); LoggingSystem system = LoggingSystem .get(LoggingSystem.class.getClassLoader()); try { ResourceUtils.getURL(logConfig).openStream().close(); // Three step initialization that accounts for the clean up of the logging // context before initialization. Spring Boot doesn't initialize a logging // system that hasn't had this sequence applied (since 1.4.1). system.cleanUp(); system.beforeInitialize(); system.initialize(new LoggingInitializationContext(environment), logConfig, logFile); } catch (Exception ex) { PropertySourceBootstrapConfiguration.logger .warn("Error opening logging config file " + logConfig, ex); } } }
@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); } };
logger.info("注册默认数据源成功"); List<Map> configs = binder.bind("spring.datasource.cluster", Bindable.listOf(Map.class)).get();
private ClientProperties getClientProperties(ConditionContext context) { ClientProperties clientProperties = new ClientProperties(context.getEnvironment()); Binder.get(context.getEnvironment()).bind("spring.boot.admin.client", Bindable.ofInstance(clientProperties)); return clientProperties; } }
@Bean(name = CONFIG_SINGLETON) public Singleton<JasyptEncryptorConfigurationProperties> configProps( @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") final EnvCopy envCopy, final ConfigurableBeanFactory bf) { return new Singleton<>(() -> { final BindHandler handler = new IgnoreErrorsBindHandler(BindHandler.DEFAULT); final MutablePropertySources propertySources = envCopy.get().getPropertySources(); final Binder binder = new Binder(ConfigurationPropertySources.from(propertySources), new PropertySourcesPlaceholdersResolver(propertySources), ApplicationConversionService.getSharedInstance(), bf::copyRegisteredEditorsTo); final JasyptEncryptorConfigurationProperties config = new JasyptEncryptorConfigurationProperties(); final ResolvableType type = ResolvableType.forClass(JasyptEncryptorConfigurationProperties.class); final Annotation annotation = AnnotationUtils.findAnnotation(JasyptEncryptorConfigurationProperties.class, ConfigurationProperties.class); final Annotation[] annotations = new Annotation[] {annotation}; final Bindable<?> target = Bindable.of(type).withExistingValue(config).withAnnotations(annotations); binder.bind("jasypt.encryptor", target, handler); return config; }); }
/** * Create a new {@link Bindable} {@link Set} of the specified element type. * @param <E> the element type * @param elementType the set element type * @return a {@link Bindable} instance */ public static <E> Bindable<Set<E>> setOf(Class<E> elementType) { return of(ResolvableType.forClassWithGenerics(Set.class, elementType)); }
@SuppressWarnings("unchecked") private Map<String, Map<String, String>> getDbInstanceConfigurations() { Map<String, Object> subProperties = Binder.get(this.environment) .bind(PREFIX, Bindable.mapOf(String.class, Object.class)).orElseGet(Collections::emptyMap); Map<String, Map<String, String>> dbConfigurationMap = new HashMap<>(subProperties.keySet().size()); for (Map.Entry<String, Object> subProperty : subProperties.entrySet()) { String instanceName = subProperty.getKey(); if (!dbConfigurationMap.containsKey(instanceName)) { dbConfigurationMap.put(instanceName, new HashMap<>()); } Object value = subProperty.getValue(); if (value instanceof Map) { Map<String, String> map = (Map) value; for (Map.Entry<String, String> entry : map.entrySet()) { dbConfigurationMap.get(instanceName).put(entry.getKey(), entry.getValue()); } } else if (value instanceof String) { String subPropertyName = extractConfigurationSubPropertyName(subProperty.getKey()); if (StringUtils.hasText(subPropertyName)) { dbConfigurationMap.get(instanceName).put(subPropertyName, (String) subProperty.getValue()); } } } return dbConfigurationMap; }
private List<City> getCities() { Properties yaml = loadCitiesYaml(); MapConfigurationPropertySource source = new MapConfigurationPropertySource(yaml); return new Binder(source).bind("cities", Bindable.listOf(City.class)).get(); }
public static void bind(Object o, Map<String, Object> properties, String configurationPropertyName, String bindingName, Validator validator, ConversionService conversionService) { Object toBind = getTargetObject(o); new Binder(Collections.singletonList(new MapConfigurationPropertySource(properties)), null, conversionService) .bind(configurationPropertyName, Bindable.ofInstance(toBind)); if (validator != null) { BindingResult errors = new BeanPropertyBindingResult(toBind, bindingName); validator.validate(toBind, errors); if (errors.hasErrors()) { throw new RuntimeException(new BindException(errors)); } } }
public static void main(String[] args) { // Fluent API 构建新 Bindable 对象(不变) Bindable bindable = Bindable.of(int.class) .withExistingValue(1) .withAnnotations(); echo(bindable); }