首页 > 解决方案 > 如何在 Spring Boot 1 应用程序中查找未使用的属性

问题描述

在 Spring Boot 1 应用程序中是否有办法知道 Spring Boot 应用程序使用的有效属性与使用 YAML 设置的所有属性、系统属性...

理想情况下,如果我们在框架中维护任何过时的属性,我想在 ApplicationListener 类中检测到这一点并阻止应用程序启动。

感谢您的帮助,

埃里克

标签: javaspringspring-boot

解决方案


当我有同样的需求时,我所做的是创建自己的 PropertyPlaceholderConfigurer:

public class DisplayablePropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

    private static final Logger log = LoggerFactory.getLogger(DisplayablePropertyPlaceholderConfigurer.class);

    private int processedNum;

    private HashSet<String> propertyNames = new HashSet<>();

    @Override
    protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess, StringValueResolver valueResolver) {
        super.doProcessProperties(beanFactoryToProcess, valueResolver);
    }

    @Override
    protected String resolvePlaceholder(String placeholder, Properties props, int systemPropertiesMode) {
        return super.resolvePlaceholder(placeholder, props, systemPropertiesMode);
    }

@Override
protected String resolvePlaceholder(String placeholder, Properties props) {
    propertyNames.add(placeholder);
    return super.resolvePlaceholder(placeholder, props);
}

    @Override
    protected String resolveSystemProperty(String key) {
        return super.resolveSystemProperty(key);
    }

    public HashSet<String> getPropertyNames() {
        return propertyNames;
    }
}

然后,您可以注册一些 CommandLineListener 或 ApplicationEvent 侦听器以在应用程序启动时调用 getPropertyNames()。

之后,您将获得已使用属性的列表。这是一个很好的起点,不是吗?您可以对这两个列表进行排序并进行比较以过滤掉未使用的属性。


推荐阅读