如何将属性转换为PropertySources?

时间:2017-11-07 06:06:18

标签: spring spring-boot

在春季启动1.4.2.RELEASE中,PropertiesConfigurationFactory有方法setProperties(Properties properties) 所以我的代码可以写成如下:

public Map<String, CacheProperties> resolve() {
    Map<String, Object> cacheSettings = resolveCacheSettings();
    Set<String> beanNames = resolveCacheManagerBeanNames(cacheSettings);
    Map<String, CacheProperties> cachePropertiesMap = new HashMap<>(beanNames.size());

    MutablePropertySources propertySources = new MutablePropertySources();
    propertySources.addFirst(new MapPropertySource("cache", cacheSettings));
    beanNames.forEach(beanName -> {
        CacheProperties cacheProperties = new CacheProperties();
        PropertiesConfigurationFactory<CacheProperties> factory = new PropertiesConfigurationFactory<>(cacheProperties);
        Properties properties = new Properties();
        properties.putAll(PropertySourceUtils.getSubProperties(propertySources, beanName));
        factory.setProperties(properties);
        factory.setConversionService(environment.getConversionService());
        try {
            factory.bindPropertiesToTarget();
            cachePropertiesMap.put(beanName, cacheProperties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });

    return cachePropertiesMap;
}

但是当我升级到spring boot 1.5.8.RELEASE。 PropertiesConfigurationFactory已将方法setProperties(Properties properties)更改为setPropertySources(PropertySources propertySources)

所以我改变了我的代码:

public Map<String, CacheProperties> resolve() {
    Map<String, Object> cacheSettings = resolveCacheSettings();
    Set<String> beanNames = resolveCacheManagerBeanNames(cacheSettings);
    Map<String, CacheProperties> cachePropertiesMap = new HashMap<>(beanNames.size());

    MutablePropertySources propertySources = new MutablePropertySources();
    propertySources.addFirst(new MapPropertySource("cache", cacheSettings));
    beanNames.forEach(beanName -> {
        CacheProperties cacheProperties = new CacheProperties();
        PropertiesConfigurationFactory<CacheProperties> factory = new PropertiesConfigurationFactory<>(cacheProperties);
        //Properties properties = new Properties();
        //properties.putAll(PropertySourceUtils.getSubProperties(propertySources, beanName));
        //factory.setProperties(properties);
        factory.setPropertySources(propertySources);
        factory.setConversionService(environment.getConversionService());
        try {
            factory.bindPropertiesToTarget();
            cachePropertiesMap.put(beanName, cacheProperties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });

    return cachePropertiesMap;
}

但这不起作用......

任何人都可以帮助我吗?如何将属性转换为PropertySources?

1 个答案:

答案 0 :(得分:0)

...解决

我在factory.setTargetName(beanName);之前添加factory.setPropertySources(propertySources);,效果很好。