Reputation: 41
Is it possible to merge multiple configuration properties into a single List of Strings?
Lets say I want to configure supported extensions, like this:
application.extension.pdf=pdf
application.extension.txt=txt
application.extension.docx=docx
And at runtime, it loads like this:
List<String> extensions = {"pdf","txt","docx"}
And then I can check if the list contains some extension. A Set could work too.
Upvotes: 1
Views: 1452
Reputation: 205
You can use a bean which does the load for you and fills a map with the properties.
PropertyFile:
application.extensions.map.pdf=pdf
application.extensions.map.txt=txt
application.extensions.map.docx=docx
Bean:
@Component
@ConfigurationProperties("application.extensions")
public class ExtensionMapper {
private Map<String, String> map = new LinkedHashMap<>();
}
This may be usefull in mapping context, where you need key and value.
(Be aware of the updated property path)
Upvotes: 1
Reputation: 18568
Let's assume you have a file called supported_extensions.props in a folder of your choice having the content you posted. Then you can read the lines of the file, split them by "="
and take the last part of the resulting array, which is the extension itself. Try these lines of code:
public static void main(String[] args) {
String filePathString = "Y:\\our\\folder\\supported_extensions.props";
Path filePath = Paths.get(filePathString);
List<String> extensionProperties = new ArrayList<>();
try {
extensionProperties = Files.readAllLines(filePath);
} catch (IOException e) {
e.printStackTrace();
}
List<String> extensions = new ArrayList<>();
extensionProperties.forEach(extensionProperty -> {
String extension = extensionProperty.split("=")[1];
extensions.add(extension);
});
extensions.forEach(extension -> {
System.out.println(extension);
});
}
You have to include these imports to make it work:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Consider the hint(s) given in the comments below your question, they are not unimportant!
Upvotes: 0