Reputation: 951
The current implementation is :-
public static final List<Integer> validCodes = Collections.unmodifiableList(Arrays.asList(110, 210, 310,510,610));
However, I am not happy with this approach as this of hard coded. I want to make it configurable instead of hard-coded. I suppose reading this values from the yaml file would solve my problem.
But how do I define a list of Integer in the yaml file and real it using @value. I can find a lot of example about reading list of strings but not integers.
Upvotes: 2
Views: 9163
Reputation: 150
Within the application.yml
file, define the config variable as follows.
my_integers: 1231,12323,12321
then use the @Value
annotation to make to an Integer list as follows.
@Value("#{'${my_integers}'.split(',')}")
private List<Integer> myIntegers;
Spring does the rest. You only need to use myIntegers
with your need.
Happy coding....
PS: I have used spring boot 2.0.*
Upvotes: 1
Reputation: 1695
One way:
Let's say if the properties file contains
intArr={1,2,3}
Then @Value
can be used like:
@Value("#{${intArr}}")
Integer[] intArr;
Second way:
If the property contains comma separated values as:
intArr: [1, 2, 3]
Then the annotation code would be:
@Value("${intArr}")
private int[] intArr;
Edit:
You can configure ConversionServiceFactoryBean
which activates the new configuration service which supports converting String to Collection types.
By activating this, it will support following kind of conversion:
intArray= 1, 2, 3, 4
And the following code:
@Value("${intArray}")
private List<Integer> myList;
Ref here
Upvotes: 0
Reputation: 832
You can used following method for getting all available properties from YML file. When you used following method, you have to add following jar into your build script.
compile group: 'org.yaml', name: 'snakeyaml', version: '1.12'
I think this will help you to continue your task.
private Map<String, Object> loadYMLData() {
Map<String, Object> result = new HashMap<String, Object>();
try {
String fileName = "{{YAMAL FILE NAME}}.yml";
Yaml yaml = new Yaml();
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
InputStream ios = new FileInputStream(file);
// Parse the YAML file and return the output as a series of Maps and Lists
result = (Map<String, Object>) yaml.load(ios);
System.out.println(result.toString());
} catch (Exception e) {
logger.error("Error==>", e);
}
return result;
}
Upvotes: 0