Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically Trim Trailing White Space for properties in Props file loaded into Spring

I'm using PropertiesFactoryBean to load properties from a typical Properties file. Is there anyway to get Spring to automatically trim trailing white space from the prop value?

like image 775
Johnny Avatar asked Aug 11 '11 19:08

Johnny


3 Answers

As this can often be a source of confusion when using Spring Boot, I want to add that you do not need XML configuration to provide your own PropertyPlaceholderConfigurer.

Simply put this in your main class:

  @Bean
  public static PropertySourcesPlaceholderConfigurer createPropertyConfigurer()
  {
    PropertySourcesPlaceholderConfigurer propertyConfigurer = new PropertySourcesPlaceholderConfigurer();
    propertyConfigurer.setTrimValues(true);
    return propertyConfigurer;
  }

This is sufficient for trimming the values from application.properties.

like image 78
Thomas Kainrad Avatar answered Oct 18 '22 00:10

Thomas Kainrad


You can customize the Properties loading functionality by passing in a custom PropertiesPersister into your PropertiesFactoryBean configuration. The PropertiesPersister instance is used by the PropertiesFactoryBean to parse the Properties file data. The default implementation follows the native parsing of java.util.Properties. You can customize the parsing logic by providing your own implementation of the PropertiesPersister interface.

like image 28
Kris Babic Avatar answered Oct 18 '22 00:10

Kris Babic


As Chad said, Spring solved this problem with version 4.3RC1. But you need to manually set on trim function with parameter "trimValues" like so (default if "false"):

 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="trimValues" value="true"/>
   <property name="locations">
       <list>
        ...
       </list>
   </property>

I do not found any documentation about this but I deduce it from Spring API.

like image 3
fante76 Avatar answered Oct 17 '22 23:10

fante76