【2020.06.22】Springboot 加载其它 yml 配置文件 使用 @PropertySource 和 @ConfigurationProperties 注解

  • yml 文档如下
active:
  author: weiyuanbao
  envList:
    - acc: 10766
      a: 10.11
      erl: 10.167

    - acance: 10.8766
      accier: 10.101


  • 使用 @PropertySource 和 @ConfigurationProperties 注解 将配置加载为一个 Bean

import com.manhattan.autotest.config.MixPropertySourceFactory;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.List;
import java.util.Map;

/**
 * @author weiyuanbao
 * @email [email protected]
 * @date 2020/6/22 上午10:37
 * @description:
 */
@Data
@Configuration
@PropertySource(value = {"classpath:active.yml"}, factory = MixPropertySourceFactory.class)
@ConfigurationProperties(prefix = "active")
public class EnvUrl {
    public String author;
    public List<Map<String, String>> envList;
    // public Map env1;
    // public Map env2;

}

  • Springboot @PropertySource 不支持加载 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 org.springframework.lang.Nullable;

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

public class MixPropertySourceFactory extends DefaultPropertySourceFactory {
    /**
     * Create a {@link PropertySource} that wraps the given resource.
     *
     * @param name     the name of the property source
     * @param resource the resource (potentially encoded) to wrap
     * @return the new {@link PropertySource} (never {@code null})
     * @throws IOException if resource resolution failed
     */
    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        String resourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
        if (resourceName.endsWith(".yml") || resourceName.endsWith(".yaml")) {
            List<PropertySource<?>> yamlSources = new YamlPropertySourceLoader().load(resourceName, resource.getResource());
            return yamlSources.get(0);
        } else {
            return new DefaultPropertySourceFactory().createPropertySource(name, resource);
        }
    }
}
  • 测试
@Autowired
EnvUrl envUrl;

@Test
    void test() {
        System.out.println(envUrl.toString());
        System.out.println(envUrl.author);
        System.out.println(envUrl.envList.toString());
    }

你可能感兴趣的:(Spring)