如果您使用的是最新的 Spring 框架版本(我相信是 Spring 3.1+),则不需要在 SpringEL 中进行字符串拆分,
只需在 Spring 的 Configuration 类中添加 PropertySourcesPlaceholderConfigurer 和 DefaultConversionService (带有注释的 Configuration ),例如,
@Configuration
public class AppConfiguration {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean public ConversionService conversionService() {
return new DefaultConversionService();
}
}
在你的课堂上
@Value("${list}")
private List<String> list;
或者,如果您想要这样做,请在构造函数的参数上使用 @Value 注释。
最后在属性文件中
list=A,B,C,D,E
如果没有 DefaultConversionService,当您将值注入字段时,您只能将逗号分隔的字符串放入字符串数组中,但是 DefaultConversionService 为您做了一些方便的魔术,并将它们添加到 Collection、Array 等中(如果您愿意,请检查实现想了解更多)
With these two, it even handles all the redundant whitespaces including newline, so you don't need to add additional logics to trim them.