方式一:读取使用逗号分隔的数组
application.yml
user: # 逗号分隔 countries: China, American, Germany
直接使用@Value
读取配置信息
@Value("${user.countries}") private String[] countryArray;
方式二:读取yaml的数组
application.yml
user: # 数组 languages: - zh - en - de
使用配置类读取配置信息
LanguageConfig.java
package com.example.demo.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; @Component @ConfigurationProperties(prefix = "user") public class LanguageConfig { private List<String> languages; public List<String> getLanguages() { return languages; } public void setLanguages(List<String> languages) { this.languages = languages; } }
使用自动注入配置类
@Autowired private LanguageConfig languageConfig;
完整使用示例
package com.example.demo; import com.example.demo.config.LanguageConfig; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import java.util.stream.Stream; @SpringBootTest class ApplicationTests { @Autowired private LanguageConfig languageConfig; @Value("${user.countries}") private String[] countryArray; @Test void testLanguageConfig() { System.out.println(languageConfig.getLanguages()); // [zh, en, de] Stream.of(countryArray).forEach(System.out::println); // China // American // Germany } }
参考