gpt4 book ai didi

java - 如何在 Spring 中使用 @ConfigurationProperties 加载名称值属性

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:43:57 26 4
gpt4 key购买 nike

我的属性文件有如下内容

config.entry[0]=X-FRAME-OPTIONS,SAMEORIGIN

config.entry[1]=Content-Security-Policy,Frame-Ancestors 'self'

我希望将其加载到配置类中,我可以在其中将逗号分隔值作为键、值对加载到集合中。如何在 Spring 3 中使用 @ConfigurationProperties 实现这一点?

Entries = config.getEntry() 应该给我一个集合,以便我可以迭代并获取属性文件中定义的名称值对列表

for(Entry<String,String> index : config.getEntry().entryset()) {
index.getKey(); // Should Give - X-FRAME-OPTIONS
index.getValue(); // Should Give - SAMEORIGIN
}

我应该如何定义将以这种方式使用属性文件中的值 Autowiring 的 Config 类?

以下实现,抛出 Spring 异常 “无法将类型 [java.lang.String] 的值转换为所需类型 [java.util.Map]” 属性 'entry[0]':否找到匹配的编辑器或转换策略]

@Component
@ConfigurationProperties("config")
public class MyConfiguration {

private Map<String,Map<String,String>> entry = new LinkedHashMap<String,Map<String,String>>();

//getter for entry

//setter for entry
}

最佳答案

您可以尝试使用 @PostConstruct 注解,它会在 bean 构建完成后被调用。您可以在此处加载配置文件并根据需要更新 map 。

例如:

@Component
public class Config {
private Map<String, String> entry = new LinkedHashMap<String, String>();

@PostConstruct
private void init() throws IOException {
try (InputStream input = ClassUtils.getDefaultClassLoader().getResourceAsStream("config.properties")) {
for (String line : IOUtils.readLines(input)) {
// change the logic as per your need
String[] keyValue = line.split("=")[1].split(",");
entry.put(keyValue[0], keyValue[1]);
}
}
}
}

关于java - 如何在 Spring 中使用 @ConfigurationProperties 加载名称值属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29921658/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com