【问题标题】:Automatically trim trailing white space for properties in properties file自动修剪属性文件中属性的尾随空格
【发布时间】:2019-09-25 09:49:47
【问题描述】:

Spring 不会修剪属性文件中给出的值。根据这里的讨论,看起来他们是故意留下来的。 但是,在我们的项目中,我们希望在应用程序使用之前自动修剪这些值。

我正在使用 2.1.4.RELEASE。

我尝试添加以下 Bean 配置

@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;
}

由于此设置,它无法加载属性文件并引发以下异常

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)

有人试过解决这个问题吗?

我参考了以下链接,但没有得到太多帮助。

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

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

【问题讨论】:

  • 你的 spring boot 版本是多少?
  • @clevertension 2.1.4.RELEASE

标签: java spring-boot properties-file


【解决方案1】:

一种简单的方法是“破解” spEl 表达式以强制使用 String.trim() 函数。

假设您在application.properties 文件中有一个属性test.myvalue 等于azerty (带有尾随空格),那么您可以像这样在您的类中注入这个属性:

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

一旦注入到您的类中,生成的myvalue 将等于azerty(没有尾随空格)。

显然,这种修剪不会全局设置为您应用中的所有注入值,您必须对所有注入值执行此操作,但我认为这种方法提供了更大的灵活性。

【讨论】:

    猜你喜欢
    • 2011-10-25
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2014-05-07
    相关资源
    最近更新 更多