Java Spring PropertyPlaceholderConfigurer 以及如何在属性文件中 trim whitespaces/tabs

Java Spring PropertyPlaceholderConfigurer and how to trim whitespaces/tabs in properties file

我有一个 属性 文件,由 PropertyPlaceholderConfigurer 以 classic 方式管理:

<bean id="propertyConfigurer"    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location" value="classpath:mail.properties" /> 
</bean>

<bean id="jobDataPathUtils"    class="com.hello.test.DataPathUtils">
    <property name="host" value="${smtp.host}" />
    <property name="port" value="${smtp.port}" />
    <property name="username" value="${smtp.user}" />
    <property name="password" value="${smtp.pass}" />
</bean>

问题是我在 .properties 文件中有很多 String 属性,大约 30 个条目,如果有人在 属性 值的末尾添加了一个表格,应用程序无法正确使用这些属性。在使用它之前,我想 trim 每个 属性 值。我可以在 DataPathUtils class 中的每个 属性 上使用 .trim() 手动完成此操作,但我想知道是否有任何其他方法可以通过 PropertyPlaceholderConfigurer 或.. .?

提前谢谢你,

  • 我认为您的数据输入方式有尾随空格需要解决。
  • 如果无法控制源,那么您需要扩展 PropertyPlaceholderConfigurer 并 trim 它 processProperties()。 使用这种方法,您可以在将来根据需要进行更改,例如从数据库中获取数据或更改特定的键值对或缓存。

            public class CustomPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
              /**  
            * Map that hold all the properties.
                 */
            private Map<String, String> propertiesMap; 
            /**
             * Iterate through all the Propery keys and build a Map, resolve all the nested values before beuilding the map.
             */
            @Override
            protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
                super.processProperties(beanFactory, props);
    
                propertiesMap = new HashMap<String, String>();
                for (Object key : props.keySet()) {
                    String keyStr = key.toString();
                    String valueStr = prop.getProperty(keyStr);
                    propertiesMap.put(keyStr.trim(), valueStr.trim());
                }
            } 
    
    
            public String getProperty(String name) {
                return propertiesMap.get(name).toString();
            }