gpt4 book ai didi

spring-boot - 如何根据输入从 yml 获取值?

转载 作者:行者123 更新时间:2023-12-03 23:48:08 25 4
gpt4 key购买 nike

我正在使用 spring-boot-starter-web 最新版本 2.2.6.RELEASE。我需要根据我的输入而不是 @value 从 yml 文件中获取值。

如果计数为100,需要得到以下值

key1: value1 100
key2: value2 100

如果计数为1000,需要得到以下值
key1: value1 1000
key2: value2 1000

我怎样才能做到这一点?

我的 application.yml 文件,
config:
host: http://myhost
count-100:
key1: value1 100
key2: value2 100
count-1000:
key1: value1 1000
key2: value2 1000
count-10000:
key1: value1 10000
key2: value2 10000

Java代码,
int count = myObject.getCount();

if (count >= 100) {
// this needs to fill from application.yml
key1 = "";
key2 = 0;
} else if (count >=1000 && count <= 10000) {
key1 = "";
key2 = 0;
} else {
key1 = "";
key2 = 0;
}

非常感谢这里的任何输入。

最佳答案

使用 @ConfigurationProperties加载计数值。

我建议更改您的应用程序 yml 以使用计数作为键,然后使用不同的计数。

就像是

config:
host: http://myhost
counts:
100:
key1: value1 100
key2: value2 100
1000:
key1: value1 1000
key2: value2 1000
10000:
key1: value1 10000
key2: value2 10000

创建一个 Counts类(class)
@Configuration
@ConfigurationProperties("config")
public class Counts {
private final Map<Integer, Map<String, String>> counts;

public Counts(Map<Integer, Map<String, String>> counts) {
this.counts = counts;
}

public Map<Integer, Map<String, String>> getCounts() {
return counts;
}
}

Java代码
//Autowire Counts class

int count = myObject.getCount();

Map<Integer, Map<String, String>> countMap = counts.getCounts().get(count);
key1 = countMap.get("key1");
key2 = countMap.get("key2");
if (count >= 100) {

} ....

如果您想保留您的应用程序 yml,您可以使用
@Configuration
@ConfigurationProperties("config")
public class Counts {

private final Map<String, String> count100;

private final Map<String, String> count1000;

private final Map<String, String> count10000;

public Counts(Map<String, String> count100, Map<String, String> count1000, Map<String, String> count10000) {
this.count100 = count100;
this.count1000 = count1000;
this.count10000 = count10000;
}

public Map<String, String> getCount1000() {
return count1000;
}

public Map<String, String> getCount100() {
return count100;
}

public Map<String, String> getCount10000() {
return count10000;
}
}

Java代码
    //Autowire Counts class

int count = myObject.getCount();

if (count >= 100) {
Map<String, String> count100Map = counts.getCount100();
key1 = count100Map.get("key1");
key2 = count100Map.get("key2");;
} ....

关于spring-boot - 如何根据输入从 yml 获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61251553/

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