org.springframework.core.env.PropertyResolver Java Examples

The following examples show how to use org.springframework.core.env.PropertyResolver. 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: IdUtils.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #2
Source File: RelaxedPropertyResolverBootstrap.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(
                    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();
}
 
Example #3
Source File: PropertyUtil.java    From dk-foundation with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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);
}
 
Example #4
Source File: IOProcessorTest.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: MultivaluedPropertyResolver.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: AnnotationUtils.java    From spring-context-support with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #7
Source File: PlaceHoldersResolver.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example #8
Source File: ConfigInspectorController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
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;
}
 
Example #9
Source File: SpringUtils.java    From onetwo with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #10
Source File: PropertyUtil.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #11
Source File: MultivaluedPropertyResolver.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
    return resolvePlaceholdersStack(text,
            PropertyResolver::resolvePlaceholders,
            PropertyResolver::resolveRequiredPlaceholders,
            t -> !t.contains("${"));
}
 
Example #12
Source File: ResourceEditor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #13
Source File: NacosBeanUtils.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #14
Source File: SpringBootBindUtil.java    From mapper-boot-starter with MIT License 5 votes vote down vote up
@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);
    }
}
 
Example #15
Source File: PropertySourcesUtils.java    From spring-context-support with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #16
Source File: AbstractEmailTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Bean
public PropertiesParser propertiesParser(PropertyResolver propertyResolver) {
    return new DefaultPropertiesParser() {
        @Override
        public String parseProperty(String key, String value, PropertiesLookup properties) {
            return propertyResolver.getProperty(key);
        }
    };
}
 
Example #17
Source File: ResourceArrayPropertyEditor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #18
Source File: ResourceArrayPropertyEditor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #19
Source File: AbstractODataTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Bean
public PropertiesParser propertiesParser(PropertyResolver propertyResolver) {
    return new DefaultPropertiesParser() {
        @Override
        public String parseProperty(String key, String value, PropertiesLookup properties) {
            return propertyResolver.getProperty(key);
        }
    };
}
 
Example #20
Source File: ResourceArrayPropertyEditor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #21
Source File: TrimouTemplateAvailabilityProvider.java    From trimou with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: SpringBootBindUtil.java    From mapper-boot-starter with MIT License 5 votes vote down vote up
@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);
    }
}
 
Example #23
Source File: N2oConfigBuilder.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #24
Source File: AbstractHibernateConnectionSourceFactory.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #25
Source File: SpringBootBindUtil.java    From Mapper with MIT License 5 votes vote down vote up
@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);
    }
}
 
Example #26
Source File: FormValidatorTest.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #27
Source File: AbstractHibernateDatastore.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #28
Source File: ResourceEditor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #29
Source File: DubboAutoConfiguration.java    From dubbo-spring-boot-project with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #30
Source File: ResourceEditor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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, PropertyResolver propertyResolver,
		boolean ignoreUnresolvablePlaceholders) {

	Assert.notNull(resourceLoader, "ResourceLoader must not be null");
	this.resourceLoader = resourceLoader;
	this.propertyResolver = propertyResolver;
	this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
}