Spring Boot 提供了两种配置数组的方式:
一、-
分隔数组多个值
user:
languages:
- zh
- en
- de
代码引用
package com.example.demo;
import java.util.stream.Stream;
import javax.annotation.PostConstruct;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "user")
public class LanguageConfig {
private String[] languages;
public String[] getLanguages() {
return this.languages;
}
public void setLanguages(String[] languages) {
this.languages = languages;
}
@PostConstruct
public void postConstruct() {
Stream.of(languages).forEach(System.out::println);
}
}
说明:
- 以上代码使用数组
array
,也可以使用List
或Set
,需要注意Set
是无序的; - 此方式需要使用
ConfigurationProperties
注解,不能使用@Value
注解,注意ConfigurationProperties
注解前缀属性prefix
的值; Getter
和Setter
方法不能省略。
二、,
分隔数组多个值
user:
countries: China, American, Germany
代码引用
package com.example.demo;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CountryConfig {
@Value("${user.countries}")
private String[] countryArray;
@Value("${user.countries}")
private List<String> countryList;
@Value("${user.countries}")
private Set<String> countrySet;
@PostConstruct
public void postConstruct() {
System.out.println("Country array:");
Stream.of(countryArray).forEach(System.out::println);
System.out.println("Country list:");
countryList.forEach(System.out::println);
System.out.println("Country set:");
countrySet.forEach(System.out::println);
}
}