Spring Boot 11 : 配置文件读取

ConfigurationProperties dependency

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

system-config.yml

diver:
  authorName: 鱼点困
  authorAge: 1
  authorAddress: ZheJiang HangZhou

配置类

/**
 * 自定义 Bean
 *
 * @Author YangXuyue
 * @Date 2018/09/05 00:04
 */
@Component
// prefix用来选择属性的前缀
@ConfigurationProperties(prefix = "diver")
// 配置文件路径
@PropertySource(value = "classpath:config/system-config.yml", encoding = "utf-8", factory = YmlPropertySourceFactory.class)
public class SystemConfig {

    /*
    // 加载资源的名称
    String name() default "";

    // 加载资源的路径,可使用classpath,如:  "classpath:/config/test.yml"
    // 除使用classpath外,还可使用文件的地址,如:"file:/rest/application.properties"
    String[] value();

    // 此属性为根据资源路径找不到文件后是否报错, 默认为是 false
    boolean ignoreResourceNotFound() default false;

    // 此为读取文件的编码, 若配置中有中文建议使用 'utf-8'
    String encoding() default "";

    // 关键:此为读取资源文件的工程类, 默认为: PropertySourceFactory.class
    Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
     */

    /*
    @PropertySource 不支持 yml。
    对于properties文件,diver.author.name 映射为 authorName
     */

    /*
    如果配置在application.properties中,
    变量的值可以采用@Value("${...}")注解进行获取
     */

    /**
     * 姓名
     */
    private String authorName;
    /**
     * 年龄
     */
    private Integer authorAge;
    /**
     * 地址
     */
    private String authorAddress;


    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    // getter setter ignored
}

YmlPropertySourceFactory

/**
 * @PropertySource 解析yml文件 工厂类
 *
 * @Author YangXuyue
 * @Date 2019/04/07 13:37
 */
public class YmlPropertySourceFactory 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);
    }
}

猜你喜欢

转载自www.cnblogs.com/yang21/p/10665132.html