'Automatically trim trailing white space for properties in properties file

Spring doesn't trim the values given in properties file. As per the discussion here, it looks like they have kept in intentionally. However, in our project, we want to trim the values automatically before it is getting used in the application.

I am using 2.1.4.RELEASE.

I tried by adding following Bean configuration

@Bean
public static PropertyPlaceholderConfigurer properties() {
    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    Resource[] resources = new ClassPathResource[]{new ClassPathResource("application.properties")};
    ppc.setLocations(resources);
    ppc.setIgnoreUnresolvablePlaceholders(true);
    ppc.setTrimValues(true);
    return ppc;
}

Because of this setting, it is not able to load properties file and throwing following exception

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'kafka.groupId' in value "${kafka.groupId}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:172)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:237)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:211)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175)

Anyone has tried to solve this problem?

I referred the following links but didn't get much help.

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

https://htr3n.github.io/2018/11/spring-boot-trailing-whitespaces/



Solution 1:[1]

One easy way to do it would be to "hack" the spEl Expression to force the use of the String.trim() function.

Let's say you have a property test.myvalue equal to azerty (with trailing spaces) in the application.properties file, then you could inject this property in your class like this :

@Value("#{'${test.myvalue}'.trim()}")
String myvalue;

The resulting myvalue will be equal to azerty (no trailing spaces) once injected in your class.

Obviously this trimming won't be set globally to all injected values in your app, and you'll have to do it to all injected value, but I think this approach gives more flexibility.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Florent Dupont