【问题标题】:Spring 4 - Retrieve all propertiesSpring 4 - 检索所有属性
【发布时间】:2015-07-15 07:52:43
【问题描述】:

我想返回 Spring 应用程序中使用的所有属性的 Map。我在 SO 中发现了几个与此类似的问题,但它们与特定的属性文件有关,而我想获取所有属性。

属性应仅适用于当前应用程序 - 不适用于运行时的任何其他部分。

【问题讨论】:

    标签: spring properties-file


    【解决方案1】:

    我想出了以下解决方案。

    请注意,这里的诡计在于包含或排除什么。我本可以根据属性文件路径的某些公共部分选择包含,但在这种情况下,我选择排除 eclipse、gradle 和 jre 属性。

    我最初排除项目,但在部署到 Tomcat 时发现我不得不开始排除更多项目。相反,我更改为包含基于项目名称(始终包含公司名称)。代码已更改以反映这一点。

    这也有少量的 Java lambda 代码(双消费者),但如有必要,可以很容易地重写。

    public Map<String, Object> getProperties() throws IOException {
        if (props != null) {
            return props;
        }
        props = new HashMap<>();
        List<String> includeResourcesSubstringList = Arrays.asList(new String[] { "the_company" });
    
        PropertiesFactoryBean propsFactory = new PropertiesFactoryBean();
        PathMatchingResourcePatternResolver resResolver = new PathMatchingResourcePatternResolver(
                this.getClass().getClassLoader());
        Resource[] resources = resResolver.getResources("classpath*:/**/*");
        List<Resource> filteredResources = new ArrayList<>();
        logger.debug("Exclude resources containing: " + includeResourcesSubstringList);
        for (Resource res : resources) {
            if (res.getFilename().endsWith(".properties")) {
                logger.debug("Res item to inspect: " + res.getDescription());
                boolean includeItem = false;
                for (String include : includeResourcesSubstringList) {
                    if (res.getURI() != null && res.getURI().toASCIIString().contains(include)) {
                        includeItem = true;
                        break;
                    }
                }
                if (includeItem) {
                    logger.debug("getProperties() - Included resource: " + res.getDescription());
                    filteredResources.add(res);
                }
            }
        }
        propsFactory.setLocations(filteredResources.toArray(new Resource[0]));
        propsFactory.afterPropertiesSet();
        Properties properties = propsFactory.getObject();
        properties.forEach((key, value) -> {
            props.put((String) key, value);
        });
    
        return props;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 2021-12-30
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多