org.springframework.core.env.PropertyResolver源码实例Demo

类org.springframework.core.env.PropertyResolver源码实例Demo

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

源代码1 项目: shardingsphere   文件: PropertyUtil.java
@SuppressWarnings("unchecked")
@SneakyThrows(ReflectiveOperationException.class)
private static Object v1(final Environment environment, final String prefix, final boolean handlePlaceholder) {
    Class<?> resolverClass = Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver");
    Constructor<?> resolverConstructor = resolverClass.getDeclaredConstructor(PropertyResolver.class);
    Method getSubPropertiesMethod = resolverClass.getDeclaredMethod("getSubProperties", String.class);
    Object resolverObject = resolverConstructor.newInstance(environment);
    String prefixParam = prefix.endsWith(".") ? prefix : prefix + ".";
    Method getPropertyMethod = resolverClass.getDeclaredMethod("getProperty", String.class);
    Map<String, Object> dataSourceProps = (Map<String, Object>) getSubPropertiesMethod.invoke(resolverObject, prefixParam);
    Map<String, Object> propertiesWithPlaceholderResolved = new HashMap<>();
    for (Entry<String, Object> entry : dataSourceProps.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (handlePlaceholder && value instanceof String && ((String) value).contains(PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX)) {
            String resolvedValue = (String) getPropertyMethod.invoke(resolverObject, prefixParam + key);
            propertiesWithPlaceholderResolved.put(key, resolvedValue);
        } else {
            propertiesWithPlaceholderResolved.put(key, value);
        }
    }
    return propertiesWithPlaceholderResolved;
}
 
源代码2 项目: GreenSummer   文件: ConfigInspectorController.java
private Map<String, List<String[]>> obtainFinalValuesAndOrigin() {
    Map<String, Object> propertyMap = envEndpoint.invoke();
    PropertyResolver propertyResolver = envEndpoint.getResolver();
    Set<String> keys = new TreeSet<>();
    List<MapSpec> propertyMaps = new ArrayList<>();
    Map<String, List<String[]>> finalValues = new HashMap<>();
    findPropertyKeysFromMap(propertyMap, keys, propertyMaps);
    keys.stream().filter(propertyResolver::containsProperty).forEach(key -> {
        String finalValue = propertyResolver.getProperty(key);
        String origin = "unknown";
        for (MapSpec map : propertyMaps) {
            log.debug("{}, checking inside: {}", key, map.getName());
            if (map.getMap().containsKey(key)) {
                origin = map.getName();
                break;
            }
        }
        finalValues.putIfAbsent(origin, new ArrayList<>());
        finalValues.get(origin).add(new String[] {
            key, finalValue});
    });
    return finalValues;
}
 
源代码3 项目: n2o-framework   文件: PlaceHoldersResolver.java
@SuppressWarnings("unchecked")
private static Function<String, Object> function(Object data) {
    if (data instanceof Function) {
        return (Function<String, Object>) data;
    } else if (data instanceof PropertyResolver) {
        return ((PropertyResolver) data)::getProperty;
    } else if (data instanceof Map) {
        return ((Map) data)::get;
    } else if (data instanceof List) {
        return k -> ((List) data).get(Integer.parseInt(k));
    } else if (data != null && data.getClass().isArray()) {
        Object[] array = (Object[]) data;
        return k -> array[Integer.parseInt(k)];
    } else if (data instanceof String || data instanceof Number || data instanceof Date) {
        return k -> data;
    } else {
        try {
            Map<String, String> map = BeanUtils.describe(data);
            return map::get;
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
 
private String resolvePlaceholdersStack(String text, BiFunction<PropertyResolver, String, String> anyProcessor,
                           BiFunction<PropertyResolver, String, String> lastProcessor,
                           Predicate<String> condition) {
    if (text == null)
        return null;
    String result = text;
    for (int i = 0; i < stack.size(); i++) {
        if (condition.test(result))
            break;
        if (lastProcessor != null && i == stack.size() - 1)
            result = lastProcessor.apply(stack.get(i), result);
        else
            result = anyProcessor.apply(stack.get(i), result);
    }
    return result;
}
 
源代码5 项目: n2o-framework   文件: IOProcessorTest.java
@Test
public void testProps() throws Exception {
    //test PropertyResolver
    ReaderFactoryByMap readerFactory = new ReaderFactoryByMap();
    readerFactory.register(new BodyNamespaceEntityIO());
    IOProcessorImpl p = new IOProcessorImpl(readerFactory);
    Properties properties = new Properties();
    properties.setProperty("testProp1", "testProp1");
    PropertyResolver systemProperties = new SimplePropertyResolver(properties);
    p.setSystemProperties(systemProperties);
    testElementWithProperty(p);

    //test params
    HashMap<String, String> params = new HashMap<>();
    params.put("testProp1", "testProp1");
    MetadataParamHolder.setParams(params);
    p = new IOProcessorImpl(readerFactory);
    testElementWithProperty(p);
    MetadataParamHolder.setParams(null);
}
 
源代码6 项目: dk-foundation   文件: PropertyUtil.java
@SuppressWarnings("unchecked")
@SneakyThrows
private static Object v1(final Environment environment, final String prefix) {
    Class<?> resolverClass = Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver");
    Constructor<?> resolverConstructor = resolverClass.getDeclaredConstructor(PropertyResolver.class);
    Method getSubPropertiesMethod = resolverClass.getDeclaredMethod("getSubProperties", String.class);
    Object resolverObject = resolverConstructor.newInstance(environment);
    String prefixParam = prefix.endsWith(".") ? prefix : prefix + ".";
    Method getPropertyMethod = resolverClass.getDeclaredMethod("getProperty", String.class);
    Map<String, Object> dataSourceProps = (Map<String, Object>) getSubPropertiesMethod.invoke(resolverObject, prefixParam);
    Map<String, Object> propertiesWithPlaceholderResolved = new HashMap<>();
    for (Entry<String, Object> entry : dataSourceProps.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        if (value instanceof String && ((String) value).contains(
                PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX)) {
            String resolvedValue = (String) getPropertyMethod.invoke(resolverObject, prefixParam + key);
            propertiesWithPlaceholderResolved.put(key, resolvedValue);
        } else {
            propertiesWithPlaceholderResolved.put(key, value);
        }
    }
    return Collections.unmodifiableMap(propertiesWithPlaceholderResolved);
}
 
public static void main(String[] args) {
    ConfigurableApplicationContext context =
            new SpringApplicationBuilder(
                    RelaxedPropertyResolverBootstrap.class)
                    .properties("user.city.postCode=0571")
                    .web(false) // 非 Web 应用
                    .run(args);
    // 获取 Environment,也是 PropertyResolver 对象
    PropertyResolver environment = context.getEnvironment();
    // 属性名称前缀
    String prefix = "user.city.";
    // 创建 RelaxedPropertyResolver 实例
    RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(environment, prefix);
    // 获取松散化配置属性
    String postCode = propertyResolver.getProperty("post-code");
    System.out.println("postCode = " + postCode);
    // 关闭上下文
    context.close();
}
 
源代码8 项目: spring-cloud-commons   文件: IdUtils.java
public static String getDefaultInstanceId(PropertyResolver resolver,
		boolean includeHostname) {
	String vcapInstanceId = resolver.getProperty("vcap.application.instance_id");
	if (StringUtils.hasText(vcapInstanceId)) {
		return vcapInstanceId;
	}

	String hostname = null;
	if (includeHostname) {
		hostname = resolver.getProperty("spring.cloud.client.hostname");
	}
	String appName = resolver.getProperty("spring.application.name");

	String namePart = combineParts(hostname, SEPARATOR, appName);

	String indexPart = resolver.getProperty("spring.application.instance_id",
			resolver.getProperty("server.port"));

	return combineParts(namePart, SEPARATOR, indexPart);
}
 
源代码9 项目: spring-context-support   文件: AnnotationUtils.java
/**
 * Get the {@link Annotation} attributes
 *
 * @param annotation           specified {@link Annotation}
 * @param propertyResolver     {@link PropertyResolver} instance, e.g {@link Environment}
 * @param ignoreDefaultValue   whether ignore default value or not
 * @param ignoreAttributeNames the attribute names of annotation should be ignored
 * @return non-null
 * @since 1.0.2
 */
public static Map<String, Object> getAttributes(Annotation annotation, PropertyResolver propertyResolver,
                                                boolean ignoreDefaultValue, String... ignoreAttributeNames) {

    Map<String, Object> annotationAttributes = org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes(annotation);

    String[] actualIgnoreAttributeNames = ignoreAttributeNames;

    if (ignoreDefaultValue && !isEmpty(annotationAttributes)) {

        List<String> attributeNamesToIgnore = new LinkedList<String>(asList(ignoreAttributeNames));

        for (Map.Entry<String, Object> annotationAttribute : annotationAttributes.entrySet()) {
            String attributeName = annotationAttribute.getKey();
            Object attributeValue = annotationAttribute.getValue();
            if (nullSafeEquals(attributeValue, getDefaultValue(annotation, attributeName))) {
                attributeNamesToIgnore.add(attributeName);
            }
        }
        // extends the ignored list
        actualIgnoreAttributeNames = attributeNamesToIgnore.toArray(new String[attributeNamesToIgnore.size()]);
    }

    return getAttributes(annotationAttributes, propertyResolver, actualIgnoreAttributeNames);
}
 
源代码10 项目: onetwo   文件: SpringUtils.java
public static String resolvePlaceholders(Object applicationContext, String value, boolean throwIfNotResolved){
	String newValue = value;
	if (StringUtils.hasText(value) && DOLOR.isExpresstion(value)){
		if (applicationContext instanceof ConfigurableApplicationContext){
			ConfigurableApplicationContext appcontext = (ConfigurableApplicationContext)applicationContext;
			newValue = appcontext.getEnvironment().resolvePlaceholders(value);
		} else if (applicationContext instanceof PropertyResolver){
			PropertyResolver env = (PropertyResolver)applicationContext;
			newValue = env.resolvePlaceholders(value);
		}
		if (DOLOR.isExpresstion(newValue) && throwIfNotResolved){
			throw new BaseException("can not resolve placeholders value: " + value + ", resovled value: " + newValue);
		}
	}
	return newValue;
}
 
源代码11 项目: spring-analysis-note   文件: ResourceEditor.java
/**
 * Create a new instance of the {@link ResourceEditor} class
 * using the given {@link ResourceLoader}.
 * @param resourceLoader the {@code ResourceLoader} to use
 * @param propertyResolver the {@code PropertyResolver} to use
 * @param ignoreUnresolvablePlaceholders whether to ignore unresolvable placeholders
 * if no corresponding property could be found in the given {@code propertyResolver}
 */
public ResourceEditor(ResourceLoader resourceLoader, @Nullable PropertyResolver propertyResolver,
		boolean ignoreUnresolvablePlaceholders) {

	Assert.notNull(resourceLoader, "ResourceLoader must not be null");
	this.resourceLoader = resourceLoader;
	this.propertyResolver = propertyResolver;
	this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
}
 
源代码12 项目: mapper-boot-starter   文件: SpringBootBindUtil.java
@Override
public <T> T bind(Environment environment, Class<T> targetClass, String prefix) {
    /**
     为了方便以后直接依赖 Spring Boot 2.x 时不需要改动代码,这里也使用反射
     try {
     RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment);
     Map<String, Object> properties = resolver.getSubProperties("");
     T target = targetClass.newInstance();
     RelaxedDataBinder binder = new RelaxedDataBinder(target, prefix);
     binder.bind(new MutablePropertyValues(properties));
     return target;
     } catch (Exception e) {
     throw new RuntimeException(e);
     }
     下面是这段代码的反射实现
     */
    try {
        //反射提取配置信息
        Class<?> resolverClass = Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver");
        Constructor<?> resolverConstructor = resolverClass.getDeclaredConstructor(PropertyResolver.class);
        Method getSubPropertiesMethod = resolverClass.getDeclaredMethod("getSubProperties", String.class);
        Object resolver = resolverConstructor.newInstance(environment);
        Map<String, Object> properties = (Map<String, Object>) getSubPropertiesMethod.invoke(resolver, "");
        //创建结果类
        T target = targetClass.newInstance();
        //反射使用 org.springframework.boot.bind.RelaxedDataBinder
        Class<?> binderClass = Class.forName("org.springframework.boot.bind.RelaxedDataBinder");
        Constructor<?> binderConstructor = binderClass.getDeclaredConstructor(Object.class, String.class);
        Method bindMethod = binderClass.getMethod("bind", PropertyValues.class);
        //创建 binder 并绑定数据
        Object binder = binderConstructor.newInstance(target, prefix);
        bindMethod.invoke(binder, new MutablePropertyValues(properties));
        return target;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
private void addProperty(Map<String, Object> source, PropertyResolver resolver,
		String serviceId, String stem, String key, String... altKeys) {
	String value = resolve(resolver, serviceId, key);
	if (StringUtils.hasText(value)) {
		source.put("security.oauth2." + stem + "." + key, value);
		return;
	}
	for (String altKey : altKeys) {
		value = resolve(resolver, serviceId, altKey);
		if (StringUtils.hasText(value)) {
			source.put("security.oauth2." + stem + "." + key, value);
			return;
		}
	}
}
 
源代码14 项目: java-technology-stack   文件: ResourceEditor.java
/**
 * Create a new instance of the {@link ResourceEditor} class
 * using the given {@link ResourceLoader}.
 * @param resourceLoader the {@code ResourceLoader} to use
 * @param propertyResolver the {@code PropertyResolver} to use
 * @param ignoreUnresolvablePlaceholders whether to ignore unresolvable placeholders
 * if no corresponding property could be found in the given {@code propertyResolver}
 */
public ResourceEditor(ResourceLoader resourceLoader, @Nullable PropertyResolver propertyResolver,
		boolean ignoreUnresolvablePlaceholders) {

	Assert.notNull(resourceLoader, "ResourceLoader must not be null");
	this.resourceLoader = resourceLoader;
	this.propertyResolver = propertyResolver;
	this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
}
 
/**
 * Create a new ResourceArrayPropertyEditor with the given {@link ResourcePatternResolver}
 * and {@link PropertyResolver} (typically an {@link Environment}).
 * @param resourcePatternResolver the ResourcePatternResolver to use
 * @param propertyResolver the PropertyResolver to use
 * @param ignoreUnresolvablePlaceholders whether to ignore unresolvable placeholders
 * if no corresponding system property could be found
 */
public ResourceArrayPropertyEditor(ResourcePatternResolver resourcePatternResolver,
		@Nullable PropertyResolver propertyResolver, boolean ignoreUnresolvablePlaceholders) {

	Assert.notNull(resourcePatternResolver, "ResourcePatternResolver must not be null");
	this.resourcePatternResolver = resourcePatternResolver;
	this.propertyResolver = propertyResolver;
	this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
}
 
/**
 * Create a new ResourceArrayPropertyEditor with the given {@link ResourcePatternResolver}
 * and {@link PropertyResolver} (typically an {@link Environment}).
 * @param resourcePatternResolver the ResourcePatternResolver to use
 * @param propertyResolver the PropertyResolver to use
 * @param ignoreUnresolvablePlaceholders whether to ignore unresolvable placeholders
 * if no corresponding system property could be found
 */
public ResourceArrayPropertyEditor(ResourcePatternResolver resourcePatternResolver,
		PropertyResolver propertyResolver, boolean ignoreUnresolvablePlaceholders) {

	Assert.notNull(resourcePatternResolver, "ResourcePatternResolver must not be null");
	this.resourcePatternResolver = resourcePatternResolver;
	this.propertyResolver = propertyResolver;
	this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
}
 
@Override
public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
    return resolvePlaceholdersStack(text,
            PropertyResolver::resolvePlaceholders,
            PropertyResolver::resolveRequiredPlaceholders,
            t -> !t.contains("${"));
}
 
public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader,
        final ResourceLoader resourceLoader) {
    if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) {
        final PropertyResolver resolver =
                new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.');
        final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX);
        final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX);
        final String resourceLocation = prefix + view + suffix;
        return resourceLoader.getResource(resourceLocation).exists();
    }
    return false;
}
 
源代码19 项目: n2o-framework   文件: N2oConfigBuilder.java
@SuppressWarnings("unchecked")
public N2oConfigBuilder(T appConfig,
                        ObjectMapper objectMapper,
                        PropertyResolver propertyResolver,
                        ContextProcessor contextProcessor) {
    this.appConfig = appConfig;
    this.appConfigType = (Class<T>) appConfig.getClass();
    this.objectMapper = objectMapper;
    this.propertyResolver = propertyResolver;
    this.contextProcessor = contextProcessor;
}
 
protected <F extends ConnectionSourceSettings> HibernateConnectionSourceSettings buildSettings(String name, PropertyResolver configuration, F fallbackSettings, boolean isDefaultDataSource) {
    HibernateConnectionSourceSettingsBuilder builder;
    HibernateConnectionSourceSettings settings;
    if(isDefaultDataSource) {
        String qualified = Settings.SETTING_DATASOURCES + '.' + Settings.SETTING_DATASOURCE;
        builder = new HibernateConnectionSourceSettingsBuilder(configuration, "", fallbackSettings);
        Map config = configuration.getProperty(qualified, Map.class, Collections.emptyMap());
        settings = builder.build();
        if(!config.isEmpty()) {

            DataSourceSettings dsfallbackSettings = null;
            if(fallbackSettings instanceof HibernateConnectionSourceSettings) {
                dsfallbackSettings = ((HibernateConnectionSourceSettings)fallbackSettings).getDataSource();
            }
            else if(fallbackSettings instanceof DataSourceSettings) {
                dsfallbackSettings = (DataSourceSettings) fallbackSettings;
            }
            DataSourceSettingsBuilder dataSourceSettingsBuilder = new DataSourceSettingsBuilder(configuration, qualified, dsfallbackSettings);
            DataSourceSettings dataSourceSettings = dataSourceSettingsBuilder.build();
            settings.setDataSource(dataSourceSettings);
        }
    }
    else {
        String prefix = Settings.SETTING_DATASOURCES + "." + name;
        settings = buildSettingsWithPrefix(configuration, fallbackSettings, prefix);
    }
    return settings;
}
 
源代码21 项目: n2o-framework   文件: FormValidatorTest.java
@Override
protected void configure(N2oApplicationBuilder builder) {
    super.configure(builder);
    builder.packs(new N2oWidgetsPack(), new N2oFieldSetsPack(), new N2oControlsPack());
    PropertyResolver props = builder.getEnvironment().getSystemProperties();
    builder.validators(new FormValidator(), new FieldSetRowValidator(),
            new FieldSetColumnValidator(), new FieldSetValidator(), new FieldValidator());
}
 
/**
 * Creates {@link ServiceAnnotationBeanPostProcessor} Bean
 *
 * @param propertyResolver {@link PropertyResolver} Bean
 * @return {@link ServiceAnnotationBeanPostProcessor}
 */
@ConditionalOnProperty(prefix = DUBBO_SCAN_PREFIX, name = BASE_PACKAGES_PROPERTY_NAME)
@ConditionalOnBean(name = BASE_PACKAGES_PROPERTY_RESOLVER_BEAN_NAME)
@Bean
public ServiceAnnotationBeanPostProcessor serviceAnnotationBeanPostProcessor(
        @Qualifier(BASE_PACKAGES_PROPERTY_RESOLVER_BEAN_NAME) PropertyResolver propertyResolver) {
    Set<String> packagesToScan = propertyResolver.getProperty(BASE_PACKAGES_PROPERTY_NAME, Set.class, emptySet());
    return new ServiceAnnotationBeanPostProcessor(packagesToScan);
}
 
protected AbstractHibernateDatastore(MappingContext mappingContext, SessionFactory sessionFactory, PropertyResolver config, ApplicationContext applicationContext, String dataSourceName) {
    super(mappingContext, config, (ConfigurableApplicationContext) applicationContext);
    this.connectionSources = new SingletonConnectionSources<>(new HibernateConnectionSource(dataSourceName, sessionFactory, null, null ), config);
    this.sessionFactory = sessionFactory;
    this.dataSourceName = dataSourceName;
    initializeConverters(mappingContext);
    if(applicationContext != null) {
        setApplicationContext(applicationContext);
    }

    osivReadOnly = config.getProperty(CONFIG_PROPERTY_OSIV_READONLY, Boolean.class, false);
    passReadOnlyToHibernate = config.getProperty(CONFIG_PROPERTY_PASS_READONLY_TO_HIBERNATE, Boolean.class, false);
    isCacheQueries = config.getProperty(CONFIG_PROPERTY_CACHE_QUERIES, Boolean.class, false);

    if( config.getProperty(SETTING_AUTO_FLUSH, Boolean.class, false) ) {
        this.defaultFlushModeName = FlushMode.AUTO.name();
        defaultFlushMode = FlushMode.AUTO.level;
    }
    else {
        FlushMode flushMode = config.getProperty(SETTING_FLUSH_MODE, FlushMode.class, FlushMode.COMMIT);
        this.defaultFlushModeName = flushMode.name();
        defaultFlushMode = flushMode.level;
    }
    failOnError = config.getProperty(SETTING_FAIL_ON_ERROR, Boolean.class, false);
    markDirty = config.getProperty(SETTING_MARK_DIRTY, Boolean.class, false);
    this.tenantResolver = new FixedTenantResolver();
    this.multiTenantMode = MultiTenancySettings.MultiTenancyMode.NONE;
    this.schemaHandler = new DefaultSchemaHandler();
}
 
源代码24 项目: Mapper   文件: SpringBootBindUtil.java
@Override
public <T> T bind(Environment environment, Class<T> targetClass, String prefix) {
    /**
     为了方便以后直接依赖 Spring Boot 2.x 时不需要改动代码,这里也使用反射
     try {
     RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment);
     Map<String, Object> properties = resolver.getSubProperties("");
     T target = targetClass.newInstance();
     RelaxedDataBinder binder = new RelaxedDataBinder(target, prefix);
     binder.bind(new MutablePropertyValues(properties));
     return target;
     } catch (Exception e) {
     throw new RuntimeException(e);
     }
     下面是这段代码的反射实现
     */
    try {
        //反射提取配置信息
        Class<?> resolverClass = Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver");
        Constructor<?> resolverConstructor = resolverClass.getDeclaredConstructor(PropertyResolver.class);
        Method getSubPropertiesMethod = resolverClass.getDeclaredMethod("getSubProperties", String.class);
        Object resolver = resolverConstructor.newInstance(environment);
        Map<String, Object> properties = (Map<String, Object>) getSubPropertiesMethod.invoke(resolver, "");
        //创建结果类
        T target = targetClass.newInstance();
        //反射使用 org.springframework.boot.bind.RelaxedDataBinder
        Class<?> binderClass = Class.forName("org.springframework.boot.bind.RelaxedDataBinder");
        Constructor<?> binderConstructor = binderClass.getDeclaredConstructor(Object.class, String.class);
        Method bindMethod = binderClass.getMethod("bind", PropertyValues.class);
        //创建 binder 并绑定数据
        Object binder = binderConstructor.newInstance(target, prefix);
        bindMethod.invoke(binder, new MutablePropertyValues(properties));
        return target;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
源代码25 项目: nacos-spring-project   文件: NacosBeanUtils.java
/**
 * Register Global Nacos Properties Bean with specified name
 *
 * @param attributes the attributes of Global Nacos Properties may contain
 *     placeholders
 * @param registry {@link BeanDefinitionRegistry}
 * @param propertyResolver {@link PropertyResolver}
 * @param beanName Bean name
 */
public static void registerGlobalNacosProperties(AnnotationAttributes attributes,
		BeanDefinitionRegistry registry, PropertyResolver propertyResolver,
		String beanName) {
	if (attributes == null) {
		return; // Compatible with null
	}
	AnnotationAttributes globalPropertiesAttributes = attributes
			.getAnnotation("globalProperties");
	registerGlobalNacosProperties((Map<?, ?>) globalPropertiesAttributes, registry,
			propertyResolver, beanName);
}
 
源代码26 项目: spring-context-support   文件: AnnotationUtils.java
/**
 * Get the {@link Annotation} attributes
 *
 * @param annotationAttributes the attributes of specified {@link Annotation}
 * @param propertyResolver     {@link PropertyResolver} instance, e.g {@link Environment}
 * @param ignoreAttributeNames the attribute names of annotation should be ignored
 * @return non-null
 * @since 1.0.4
 */
public static Map<String, Object> getAttributes(Map<String, Object> annotationAttributes,
                                                PropertyResolver propertyResolver, String... ignoreAttributeNames) {

    Set<String> ignoreAttributeNamesSet = new HashSet<String>(arrayToList(ignoreAttributeNames));

    Map<String, Object> actualAttributes = new LinkedHashMap<String, Object>();

    for (Map.Entry<String, Object> annotationAttribute : annotationAttributes.entrySet()) {

        String attributeName = annotationAttribute.getKey();
        Object attributeValue = annotationAttribute.getValue();

        // ignore attribute name
        if (ignoreAttributeNamesSet.contains(attributeName)) {
            continue;
        }

        if (attributeValue instanceof String) {
            attributeValue = resolvePlaceholders(valueOf(attributeValue), propertyResolver);
        } else if (attributeValue instanceof String[]) {
            String[] values = (String[]) attributeValue;
            for (int i = 0; i < values.length; i++) {
                values[i] = resolvePlaceholders(values[i], propertyResolver);
            }
            attributeValue = values;
        }
        actualAttributes.put(attributeName, attributeValue);
    }
    return actualAttributes;
}
 
源代码27 项目: spring-context-support   文件: AnnotationUtils.java
private static String resolvePlaceholders(String attributeValue, PropertyResolver propertyResolver) {
    String resolvedValue = attributeValue;
    if (propertyResolver != null) {
        resolvedValue = propertyResolver.resolvePlaceholders(resolvedValue);
        resolvedValue = trimWhitespace(resolvedValue);
    }
    return resolvedValue;
}
 
/**
 * Get prefixed {@link Properties}
 *
 * @param propertySources  {@link PropertySources}
 * @param propertyResolver {@link PropertyResolver} to resolve the placeholder if present
 * @param prefix           the prefix of property name
 * @return Map
 * @see Properties
 * @since 1.0.3
 */
public static Map<String, Object> getSubProperties(PropertySources propertySources, PropertyResolver propertyResolver, String prefix) {

    Map<String, Object> subProperties = new LinkedHashMap<String, Object>();

    String normalizedPrefix = normalizePrefix(prefix);

    Iterator<PropertySource<?>> iterator = propertySources.iterator();

    while (iterator.hasNext()) {
        PropertySource<?> source = iterator.next();
        if (source instanceof EnumerablePropertySource) {
            for (String name : ((EnumerablePropertySource<?>) source).getPropertyNames()) {
                if (!subProperties.containsKey(name) && name.startsWith(normalizedPrefix)) {
                    String subName = name.substring(normalizedPrefix.length());
                    if (!subProperties.containsKey(subName)) { // take first one
                        Object value = source.getProperty(name);
                        if (value instanceof String) {
                            // Resolve placeholder
                            value = propertyResolver.resolvePlaceholders((String) value);
                        }
                        subProperties.put(subName, value);
                    }
                }
            }
        }
    }

    return unmodifiableMap(subProperties);
}
 
源代码29 项目: syndesis   文件: AbstractEmailTest.java
@Bean
public PropertiesParser propertiesParser(PropertyResolver propertyResolver) {
    return new DefaultPropertiesParser() {
        @Override
        public String parseProperty(String key, String value, PropertiesLookup properties) {
            return propertyResolver.getProperty(key);
        }
    };
}
 
源代码30 项目: syndesis   文件: AbstractODataTest.java
@Bean
public PropertiesParser propertiesParser(PropertyResolver propertyResolver) {
    return new DefaultPropertiesParser() {
        @Override
        public String parseProperty(String key, String value, PropertiesLookup properties) {
            return propertyResolver.getProperty(key);
        }
    };
}