Spring Boot 配置(五)数组

1,223 阅读1分钟

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,也可以使用ListSet,需要注意Set是无序的;
  • 此方式需要使用ConfigurationProperties注解,不能使用@Value注解,注意ConfigurationProperties注解前缀属性prefix的值;
  • GetterSetter方法不能省略。

二、,分隔数组多个值

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);
    }
}