如何在Spring中检测未使用的属性 [英] How to detect unused properties in Spring

查看:184
本文介绍了如何在Spring中检测未使用的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个没有注释的Spring 2.0项目。我们使用具有不同前缀和后缀的几个PropertyPlaceholderConfigurer bean来加载来自不同属性文件的属性。这很好用。

I'm working on a Spring 2.0 project, without annotations. We're using several PropertyPlaceholderConfigurer beans with different pre- and suffixes to load properties from different property files. This works beautifully.

由于属性文件和属性数量众多,我希望应用程序列出未使用的属性。这意味着,在属性文件中配置但从未在Spring应用程序上下文中引用的属性。

Because of the large number of property files and properties, I wanted the application to list the properties which are not used. That means, properties which are configured in a property file, but never referenced in the Spring application context.

我写了一个实现BeanFactoryPostProcessor的bean,并且做了一些技巧来查找在应用程序上下文中引用不同的PropertyPlaceHolderConfigurers。这给了我一个使用的属性列表。

I wrote a bean which implements BeanFactoryPostProcessor, and did some trickery to find references in the application context to the different PropertyPlaceHolderConfigurers. This gives me a list of properties which are used.

但是,我无法访问由PlaceHolderConfigurers加载的属性。因此,我无法显示未使用的属性。

However, I can not get to the properties which were loaded by the PlaceHolderConfigurers. Because of that, I can not show the properties which are NOT used.

是否有(简单)方法获取PropertyPlaceholderConfigurer的属性?关于如何解决这个问题的任何其他建议?

Is there a (simple) way to get to the properties of a PropertyPlaceholderConfigurer? Any other suggestions on how to solve this problem?

编辑:解决方案正在访问mergeProperties metod,如下所示:

Edit: The solution was accessing the mergeProperties metod, like so:

PropertyPlaceholderConfigurer ppc = 
    (PropertyPlaceholderConfigurer) applicationContext.getBean("yourBeanId");
Method m = PropertiesLoaderSupport.class.getDeclaredMethod("mergeProperties", 
            new Class[] {});
m.setAccessible(true);
Properties loadedProperties = (Properties) m.invoke(propertyPlaceHolder, null);

获取最初加载的属性,并在BeanFactoryPostProcessing期间获取beandefinitions,其余的很简单。减去两个集合,瞧:我们现在可以列出未使用的属性。

After getting the originally loaded properties, and fetching the beandefinitions during the BeanFactoryPostProcessing, the rest was simple. Subtract the two collections, and voila: We can now list the unused properties.

推荐答案

您可以尝试调用受保护的方法 mergeProperties 使用反射来获取完整的属性列表,然后,正如其他海报已经说过的那样,删除所有实际用于结束未使用属性集的属性。

You might try calling the protected method mergeProperties using reflection to get a hold of the complete list of properties, and then, as other posters have already said, remove all properties that are actually used to end up with the set of unused properties.

对于生产代码可能有点过于讨厌,但我假设你只是在单元测试设置中运行它来生成这个报告。

Probably a bit too hackish for production code, but I am assuming you would be running this only in a unit test setting to generate this report.

这篇关于如何在Spring中检测未使用的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆