Spring 不会修剪属性文件中给出的值。根据这里的讨论,看起来他们是故意保留的。 但是,在我们的项目中,我们希望在应用程序中使用它之前自动修剪值。
我正在使用 2.1.4.发布。
我尝试添加以下 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)
有人尝试过解决这个问题吗?
我参考了以下链接,但没有得到太多帮助。
自动修剪加载到 Spring 中的 Props 文件中属性的尾随空格,
https://htr3n.github.io/2018/11/spring-boot-trailing-whitespaces/
一种简单的方法是"破解"spEl 表达式以强制使用 String.trim(( 函数。
假设您在application.properties
文件中有一个等于azerty
(带有尾随空格test.myvalue
的属性,那么您可以在类中注入此属性,如下所示:
@Value("#{'${test.myvalue}'.trim()}")
String myvalue;
一旦注入到类中,生成的myvalue
将等于azerty
(无尾随空格(。
显然,这种修剪不会全局设置为应用程序中的所有注入值,您必须对所有注入的值执行此操作,但我认为这种方法提供了更大的灵活性。