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?
问题:
回答1:
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.
回答2:
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.
回答3:
You can define your own property configurer:
package your.company.package;
public class TrimPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
@Override
protected String resolvePlaceholder( String placeholder, Properties props ) {
String value = super.resolvePlaceholder( placeholder, props );
return (value != null ? value.trim() : null );
}
}
Then you must define it in your bean_config.xml
<bean id="applicationProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:main.properties" />
</bean>
<bean id="trimPropertyPlaceholderConfigurer" class="your.company.package.TrimPropertyPlaceholderConfigurer">
<property name="properties" ref="applicationProperties" />
</bean>
Another way if you're using @Value annotations to set the properties into the fields:
@Value( value = "#{applicationProperties['my.app.property'].trim()}" )
NullPointerException is thrown if the property doesn't exists in the file
回答4:
With latest Spring version(4.3+), you can simply call setTrimValues() with true when you create PropertySourcesPlaceholderConfigurer bean in your configuration. That will remove any extra leading or trailing spaces from the value you got from the properties file.