How to detect unused properties in Spring

2020-07-10 08:33发布

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.

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.

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.

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.

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

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);

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.

标签: java spring
3条回答
beautiful°
2楼-- · 2020-07-10 08:50

Couldn't you just iterate over the list of used properties and remove them from a duplicate set of all properties? That would leave the unused ones behind.

查看更多
Emotional °昔
3楼-- · 2020-07-10 08:56

How about creating your own subclass of PropertyPlaceholderConfigurer that would keep a reference to the its Properties object and provide an accessor. Your BeanFactoryPostProcessor would then be able to access each original Properties objects and combined with the list of properties which are used you could figure out the properties that were not used.

查看更多
forever°为你锁心
4楼-- · 2020-07-10 09:07

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.

查看更多
登录 后发表回答