Reputation: 2144
I am using spring-boot-starter-web latest version 2.2.6.RELEASE. I need to get value from yml file based on my input instead of @value.
If the count is 100, need to get the following values
key1: value1 100
key2: value2 100
If the count is 1000, need to get the following values
key1: value1 1000
key2: value2 1000
How can I achieve this?
My application.yml file,
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 code,
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;
}
Any inputs here highly appreciated.
Upvotes: 4
Views: 1385
Reputation: 75984
Use @ConfigurationProperties
to load the count values.
I would recommend changing your application yml to use counts as key followed by different counts.
Something like
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
Create a 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 Code
//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) {
} ....
If you like to keep your application yml you can use
@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 Code
//Autowire Counts class
int count = myObject.getCount();
if (count >= 100) {
Map<String, String> count100Map = counts.getCount100();
key1 = count100Map.get("key1");
key2 = count100Map.get("key2");;
} ....
Upvotes: 3