Spring Boot @PropertySource加载 .properties 和 .yml 配置文件中的“数组”

1,896 阅读1分钟

一、加载 .properties 配置文件

  • city.properties:src/main/resources/city.properties
city.name=Shanghai, Beijing, Hangzhou
  • City.java
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.List;

@Data
@Component
@PropertySource(value = {"classpath:city.properties"})
@ConfigurationProperties(prefix = "city")
public class City {
    private List<String> name;
}
  • CityController.java
import com.ke.myspring.entity.City;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
public class CityController {
    private final City city;

    @Autowired
    public CityController(City city) {
        this.city = city;
    }

    @RequestMapping(value = "/test/city", method = RequestMethod.GET)
    public void testCity() {
        Optional.ofNullable(city.getName()).ifPresent(l -> l.forEach(System.out::println));
    }
}
  • 输出
Shanghai
Beijing
Hangzhou

二、加载 .yml 配置文件

  • city2.yml:src/main/resources/city2.yml
city:
  name: [ 上海市, 北京市, 深圳市, 广州市, 杭州市, 西安市, 浙江市, 宝鸡市, 无锡市 ]
  • PropertySourceFactory.java:用于处理 yml 配置文件的属性资源配置
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;
import java.util.List;

public class PropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null) {
            return super.createPropertySource(name, resource);
        }
        List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
        return sources.get(0);
    }
}
  • City.java
import com.ke.myspring.config.PropertySourceFactory;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.List;

@Data
@Component
@PropertySource(value = {"classpath:city2.yml"}, factory = PropertySourceFactory.class)
@ConfigurationProperties(prefix = "city")
public class City {
    private List<String> name;
}
  • CityController.java 同上

  • 输出

上海市
北京市
深圳市
广州市
杭州市
西安市
浙江市
宝鸡市
无锡市