java - Autowiring List<List<String>> 出具有未知键长度的属性文件

标签 java spring autowired properties-file

有没有办法在从属性文件读取的另一个列表中 Autowiring 一个包含字符串的列表?我发现的困难是需要将属性值拆分为字符串列表(或数组),然后自动连接到。 我的属性文件看起来像这样:

jobFolders1=C:/Temp/originFolder, C:/Temp/trafoIn, C:/Temp/trafoOut, C:/Temp/destinationFolder
jobFolders2=C:/Temp/originFolder2, C:/Temp/trafoIn2, C:/Temp/trafoOut2, C:/Temp/destinationFolder2

现在,只要有新工作,我希望我的用户能够向该文件添加行。所以我永远不知道按键的名称,也不知道行数。 有什么方法可以将文件条目自动连接到一个列表,该列表本身包含一个包含 4 个字符串的列表(由“,”分隔)? 可能这整个方法不是最好的。如果是这样,请随时告诉我。

最佳答案

好吧,下面是一个非常“有弹性”的解决方案,尽管我认为可以更优雅地解决这个问题(根本不需要编写自定义代码):

编写一个 PropertyMapper:

@Component("PropertyMapper")
public class PropertyMapper {

@Autowired
ApplicationContext context;
@Autowired
List<List<String>> split;

public List<List<String>> splitValues(final String beanname) {
((Properties) this.context.getBean(beanname)).values().forEach(v -> {
final List<String> paths = Arrays.asList(((String) v).split(","));
paths.forEach(p -> paths.set(paths.indexOf(p), p.trim()));
this.split.add(paths);
});
return this.split;
}

像这样在 context.xml 中加载属性:

<util:properties id="testProps" location="classpath:test.properties"/>

然后将值连接到字段,使用 Spring EL 通过调用 splitValues 方法“调整”原始值:

@Value("#{PropertyMapper.splitValues('testProps')}")
private List<List<String>> allPaths;

关于java - Autowiring List<List<String>> 出具有未知键长度的属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35172574/

相关文章:

java - Spring Security - 简单的 CORS 身份验证错误

spring - 在 Spring HATEOAS 中嵌入对象而不是集合

Spring Autowiring 列表

java - 获取样式等于 x 的 id - Java - Selenium WebDriver

java - if 语句产生不正确的结果

java - 给定这段代码我将如何排序

java - 执行 "AbstractMethodError"构造函数时发生 "org.hibernate.internal.SessionFactoryImpl()"错误

java - Spring Autowired 实例在每个请求上始终相同

Spring 在没有 @Autowired 注释的构造函数中注入(inject)依赖项

java - 为什么在这种情况下,我的 Java 代码比我的 C++ 代码运行得更快?