Spring Boot中如何在application.properties与application.yml中配置Map<String,List<String>>类型参数
Hey there! Let's walk through how to handle these Spring Boot configuration scenarios clearly.
Map<String, List<String>> in application.properties In .properties files, you need a specific syntax to represent maps with list values—use square brackets [] for map keys, and commas to separate individual list items. Here's a practical example:
Suppose you pick a prefix like custom.mappings for your configuration, your application.properties would look like this:
custom.mappings[movement]=accountId,positionId,accountName custom.mappings[transaction]=transactionId,transactionName,transactionDate
To bind this configuration to a Java class, use Spring's @ConfigurationProperties annotation:
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; @Component @ConfigurationProperties(prefix = "custom.mappings") public class CustomMappingsProperties { private Map<String, List<String>> mappings; // Getters and setters public Map<String, List<String>> getMappings() { return mappings; } public void setMappings(Map<String, List<String>> mappings) { this.mappings = mappings; } }
Map<String, List<String>> in application.yml YAML shines for hierarchical structures like this—it's way more readable than properties files for nested data. For your exact requirement (where movement maps to three values and transaction maps to another three), the configuration would look like this:
custom: mappings: movement: - accountId - positionId - accountName transaction: - transactionId - transactionName - transactionDate
The same Java class from the previous section works here too—Spring Boot will automatically bind this YAML structure to your Map<String, List<String>> field. A quick tip: Add the spring-boot-configuration-processor dependency to your build file if you want IDE auto-completion for these properties.
Also, if you don't mark your properties class with @Component, don't forget to enable it in your main application class with @EnableConfigurationProperties(CustomMappingsProperties.class).
内容的提问来源于stack exchange,提问作者Debo

